src/EventSubscriber/LocaleSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  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(ParameterBagInterface $params)
  11.     {
  12.         $this->defaultLocale $params->get('kernel.default_locale');
  13.     }
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  18.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  19.         ];
  20.     }
  21.     public function onKernelRequest(RequestEvent $event)
  22.     {
  23.         $request $event->getRequest();
  24.         if (!$request->hasPreviousSession()) {
  25.             return;
  26.         }
  27.         $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  28.     }
  29. }