src/EventSubscriber/LocaleSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Contracts\Translation\TranslatorInterface;
  8. class LocaleSubscriber implements EventSubscriberInterface
  9. {
  10.     private $defaultLocale;
  11.     private $translatorInterface;
  12.     private $managedLocales;
  13.     public function __construct($defaultLocale 'en'$managedLocalesTranslatorInterface $translatorInterface)
  14.     {
  15.         $this->defaultLocale $defaultLocale;
  16.         $this->managedLocales $managedLocales;
  17.         $this->translatorInterface $translatorInterface;
  18.     }
  19.     public function onKernelRequest(RequestEvent $event)
  20.     {
  21.         $request $event->getRequest();
  22. //        if (!$request->hasPreviousSession()) {
  23. //            return;
  24. //        }
  25.         // try to see if the locale has been set as a _locale routing parameter
  26.         if ($locale $request->attributes->get('_locale')) {
  27.             $request->getSession()->set('_locale'$locale);
  28.         } else {
  29.             $sessionLocale $request->getSession()->get('_locale');
  30.             if (!$sessionLocale) {
  31.                 $browserLocale = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 02) : null;
  32.                 $sessionLocale = (($browserLocale and in_array($browserLocale$this->managedLocales)) ? $browserLocale $this->defaultLocale);
  33.             }
  34.             // if no explicit locale has been set on this request, use one from the session
  35.             $request->setLocale($sessionLocale);
  36.             $this->translatorInterface->setLocale($sessionLocale);
  37.         }
  38.     }
  39.     public static function getSubscribedEvents()
  40.     {
  41.         return [
  42.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  43.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  44.         ];
  45.     }
  46. }