vendor/sonata-project/translation-bundle/src/EventSubscriber/LocaleSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the Sonata Project package.
  5.  *
  6.  * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Sonata\TranslationBundle\EventSubscriber;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpKernel\Event\RequestEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. /**
  16.  * @author Jonathan Vautrin <jvautrin@pro-info.be>
  17.  */
  18. final class LocaleSubscriber implements EventSubscriberInterface
  19. {
  20.     private string $defaultLocale;
  21.     public function __construct(string $defaultLocale 'en')
  22.     {
  23.         $this->defaultLocale $defaultLocale;
  24.     }
  25.     public function onKernelRequest(RequestEvent $event): void
  26.     {
  27.         $request $event->getRequest();
  28.         if (!$request->hasPreviousSession()) {
  29.             return;
  30.         }
  31.         // try to see if the locale has been set as a _locale routing parameter
  32.         if ($request->attributes->has('_locale')) {
  33.             $locale = (string) $request->attributes->get('_locale');
  34.             $request->getSession()->set('_locale'$locale);
  35.             return;
  36.         }
  37.         // if no explicit locale has been set on this request, use one from the session
  38.         $request->setLocale((string) $request->getSession()->get('_locale'$this->defaultLocale));
  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. }