src/EventSubscriber/LocaleSubscriber.php line 18

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