src/EventSubscriber/LocaleSubscriber.php line 21

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