src/EventSubscriber/LocaleSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7.  
  8. class LocaleSubscriber implements EventSubscriberInterface
  9. {
  10.     private $defaultLocale;
  11.  
  12.     public function __construct($defaultLocale 'en')
  13.     {
  14.         $this->defaultLocale $defaultLocale;
  15.     }
  16.  
  17.     public function onKernelRequest(GetResponseEvent $event)
  18.     {
  19.         $request $event->getRequest();
  20.         if (!$request->hasPreviousSession()) {
  21.             return;
  22.         }
  23.         // try to see if the locale has been set as a _locale routing parameter
  24.         if ($locale $request->get('_locale')) {
  25.             $request->getSession()->set('_locale'$locale);
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.             $locale ='en';
  29.             $request->setLocale($request->getSession()->get('_locale'$locale));//$this->defaultLocale));
  30.         }
  31.     }
  32.  
  33.     public static function getSubscribedEvents()
  34.     {
  35.         return array(
  36.             // must be registered after the default Locale listener
  37.             KernelEvents::REQUEST => array(array('onKernelRequest'20)),
  38.         );
  39.     }
  40. }