src/EventSubscriber/LocaleSubscriber.php line 37

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/LocaleSubscriber.php
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class LocaleSubscriber implements EventSubscriberInterface
  8. {
  9. private $defaultLocale;
  10. public function __construct($defaultLocale = 'fr')
  11. {
  12. if(isset($_GET['lang']) && !empty($_GET['lang'])) $defaultLocale=@$_GET['lang'];
  13. $this->defaultLocale = $defaultLocale;
  14. }
  15. public function onKernelRequest(RequestEvent $event)
  16. {
  17. $request = $event->getRequest();
  18. // Return early if there is no session
  19. if (!$request->hasPreviousSession()) {
  20. return;
  21. }
  22. // Get the 'lang' attribute from the request, if available
  23. $locale = $request->attributes->get('lang');
  24. // Set the locale from the 'lang' attribute or session
  25. if ($locale) {
  26. $request->getSession()->set('_locale', $locale);
  27. $request->setLocale($locale);
  28. } else {
  29. $locale = $request->getSession()->get('_locale', $this->defaultLocale);
  30. $request->setLocale($locale);
  31. }
  32. }
  33. public static function getSubscribedEvents()
  34. {
  35. return [
  36. KernelEvents::REQUEST => [['onKernelRequest', 20]],
  37. ];
  38. }
  39. }