src/EventSubscriber/LocaleSubscriber.php line 29

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.     /**
  11.      * Constructor for the LocaleSubscriber.
  12.      *
  13.      * @param string $defaultLocale The default locale to use if none is explicitly set.
  14.      */
  15.     public function __construct(string $defaultLocale 'en')
  16.     {
  17.         $this->defaultLocale $defaultLocale;
  18.     }
  19.     /**
  20.      * Handles the kernel request event.
  21.      *
  22.      * @param RequestEvent $event The request event.
  23.      */
  24.     public function onKernelRequest(RequestEvent $event)
  25.     {
  26.         $request $event->getRequest();
  27.         if (!$request->hasPreviousSession()) {
  28.             return;
  29.         }
  30.         // Try to see if the locale has been set as a _locale routing parameter
  31.         if ($locale $request->attributes->get('_locale')) {
  32.             $request->getSession()->set('_locale'$locale);
  33.         } else {
  34.             // If no explicit locale has been set on this request, use one from the session
  35.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  36.         }
  37.     }
  38.     /**
  39.      * Returns an array of event names this subscriber wants to listen to.
  40.      *
  41.      * @return array The event names and their corresponding methods and priorities.
  42.      */
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [
  46.             // Must be registered before (i.e., with a higher priority than) the default Locale listener
  47.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  48.         ];
  49.     }
  50. }