src/EventSubscriber/LocaleSubscriber.php line 21

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. /**
  8.  * @see https://symfony.com/doc/current/session/locale_sticky_session.html
  9.  */
  10. class LocaleSubscriber implements EventSubscriberInterface
  11. {
  12.     private $defaultLocale;
  13.     public function __construct($defaultLocale 'en')
  14.     {
  15.         $this->defaultLocale $defaultLocale;
  16.     }
  17.     public function onKernelRequest(RequestEvent $event)
  18.     {
  19.         $request $event->getRequest();
  20.         if (!$request->hasPreviousSession()) {
  21.             return;
  22.         }
  23.         // try to see if the locale has been set as a _locale routing parameter
  24.         if ($locale $request->attributes->get('_locale')) {
  25.             $request->getSession()->set('_locale'$locale);
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  29.         }
  30.     }
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  35.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  36.         ];
  37.     }
  38. }