src/EventSubscriber/LocaleSubscriber.php line 18

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. // https://symfony.com/doc/current/session.html#locale-sticky-session
  7. class LocaleSubscriber implements EventSubscriberInterface
  8. {
  9.     private $defaultLocale;
  10.     public function __construct($defaultLocale 'es')
  11.     {
  12.         $this->defaultLocale $defaultLocale;
  13.     }
  14.     public function onKernelRequest(RequestEvent $event)
  15.     {
  16.         $request $event->getRequest();
  17.         if (!$request->hasPreviousSession()) {
  18.             return;
  19.         }
  20.         if ($locale $request->attributes->get('_locale')) {
  21.             $request->getSession()->set('_locale'$locale);
  22.         } else {
  23.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  24.         }
  25.     
  26.     }
  27.     public static function getSubscribedEvents()
  28.     {
  29.         return [
  30.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  31.         ];
  32.     }
  33. }