src/EventSubscriber/LocaleSubscriber.php line 30

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