src/EventSubscriber/LocaleSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/LocaleSubscriber.php
  3. // src/EventSubscriber/LocaleSubscriber.php
  4. namespace App\EventSubscriber;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  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(string $defaultLocale 'en')
  12.     {
  13.         $this->defaultLocale $defaultLocale;
  14.     }
  15.     public static function getSubscribedEvents()
  16.     {
  17.         return [
  18.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  19.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  20.         ];
  21.     }
  22.     public function onKernelRequest(RequestEvent $event)
  23.     {
  24.         $request $event->getRequest();
  25.         if (!$request->hasPreviousSession()) {
  26.             return;
  27.         }
  28.         // try to see if the locale has been set as a _locale routing parameter
  29.         if ($locale $request->attributes->get('_locale')) {
  30.             $request->getSession()->set('_locale'$locale);
  31.         } else {
  32.             // if no explicit locale has been set on this request, use one from the session
  33.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  34.         }
  35.     }
  36. }