src/EventSubscriber/LocaleSubscriber.php line 20

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\HttpFoundation\Session\Session;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class LocaleSubscriber implements EventSubscriberInterface
  9. {
  10.     private $defaultLocale;
  11.     public function __construct($defaultLocale 'en')
  12.     {
  13.         $this->defaultLocale $defaultLocale;
  14.     }
  15.     public function onKernelRequest(RequestEvent $event)
  16.     {
  17.         $request $event->getRequest();
  18.         if (!$request->hasPreviousSession()) {
  19.             return;
  20.         }
  21.         if ($request->getRequestUri() !== '/login') {
  22.             // try to see if the locale has been set as a _locale routing parameter
  23.             if ($locale $request->attributes->get('_locale')) {
  24.                 $request->getSession()->set('_locale'$locale);
  25.             } else {
  26.                 // if no explicit locale has been set on this request, use one from the session
  27.                 $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  28.             }
  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. }