src/EventSubscriber/LocaleSubscriber.php line 24

Open in your IDE?
  1. <?php 
  2. // src/App/EventSubscriber/LocaleSubscriber.php
  3. namespace App\EventSubscriber;
  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\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(GetResponseEvent $event)
  16.     public function onKernelRequest(RequestEvent $event)
  17.     {
  18.         $request $event->getRequest();
  19.         if (!$request->hasPreviousSession()) {
  20.             return;
  21.         }
  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.             // $request->setLocale($request->getLocale());
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.            // $request->setLocale($request->getSession()->get('fr', $this->defaultLocale));
  29.             $request->setLocale($this->defaultLocale);
  30.         }
  31.     }
  32.     public static function getSubscribedEvents()
  33.     {
  34.         return [
  35.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  36.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  37.         ];
  38.     }
  39. }