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

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\GetResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. /**
  16.  * @author Jonathan Vautrin <jvautrin@pro-info.be>
  17.  */
  18. final class LocaleSubscriber implements EventSubscriberInterface
  19. {
  20.     /**
  21.      * @var string
  22.      */
  23.     private $defaultLocale;
  24.     /**
  25.      * @param string $defaultLocale
  26.      */
  27.     public function __construct($defaultLocale 'en')
  28.     {
  29.         $this->defaultLocale $defaultLocale;
  30.     }
  31.     /**
  32.      * @param GetResponseEvent $event
  33.      */
  34.     public function onKernelRequest(GetResponseEvent $event)
  35.     {
  36.         $request $event->getRequest();
  37.         if (!$request->hasPreviousSession()) {
  38.             return;
  39.         }
  40.         // try to see if the locale has been set as a _locale routing parameter
  41.         if ($locale $request->attributes->get('_locale')) {
  42.             $request->getSession()->set('_locale'$locale);
  43.             return;
  44.         }
  45.         // if no explicit locale has been set on this request, use one from the session
  46.         $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  47.     }
  48.     /**
  49.      * @return array
  50.      */
  51.     public static function getSubscribedEvents()
  52.     {
  53.         return [
  54.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  55.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  56.         ];
  57.     }
  58. }