src/EventSubscriber/LocaleSubscriber.php line 24

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\GetResponseEvent;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class LocaleSubscriber implements EventSubscriberInterface
  10. {
  11.     protected $defaultLocale;
  12.     public function __construct(ParameterBagInterface $parameterBag)
  13.     {
  14.         $this->defaultLocale $parameterBag->get('locale');
  15.     }
  16.     /**
  17.      * @param RequestEvent $event
  18.      */
  19.     public function onKernelRequest(RequestEvent $event)
  20.     {
  21.         $request $event->getRequest();
  22.         if (!$request->hasPreviousSession()) {
  23.             return;
  24.         }
  25.         if ($locale $request->attributes->get('_locale')) {
  26.             $request->getSession()->set('_locale'$locale);
  27.         } else {
  28.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  29.         }
  30.     }
  31.     /**
  32.      * @return array
  33.      */
  34.     public static function getSubscribedEvents(): array
  35.     {
  36.         return [
  37.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  38.         ];
  39.     }
  40. }