src/EventSubscriber/LocaleSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8.     private $defaultLocale;
  9.     public function __construct($defaultLocale)
  10.     {
  11.         $this->defaultLocale $defaultLocale;
  12.     }
  13.     public function onKernelRequest(RequestEvent $event)
  14.     {
  15.         $request $event->getRequest();
  16.         if (!$request->hasPreviousSession()) {
  17.             $locale $this->defaultLocale;
  18.         } else {
  19.             $locale $request->getSession()->get('_locale'$this->defaultLocale);
  20.         }
  21.         $request->attributes->set('_locale'$locale);
  22.         $request->setLocale($locale);
  23.         $request->getSession()->set('_locale'$locale);
  24.     }
  25.     public static function getSubscribedEvents()
  26.     {
  27.         return [
  28.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  29.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  30.         ];
  31.     }
  32. }