vendor/symfony/http-kernel/EventListener/TranslatorListener.php line 44

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\HttpKernel\EventListener;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  15. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Symfony\Component\Translation\TranslatorInterface;
  18. use Symfony\Contracts\Translation\LocaleAwareInterface;
  19. /**
  20.  * Synchronizes the locale between the request and the translator.
  21.  *
  22.  * @author Fabien Potencier <fabien@symfony.com>
  23.  */
  24. class TranslatorListener implements EventSubscriberInterface {
  25.     private $translator;
  26.     private $requestStack;
  27.     /**
  28.      * @param LocaleAwareInterface $translator
  29.      */
  30.     public function __construct($translatorRequestStack $requestStack) {
  31.         if (!$translator instanceof TranslatorInterface && !$translator instanceof LocaleAwareInterface) {
  32.             throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.'__METHOD__LocaleAwareInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator)));
  33.         }
  34.         $this->translator $translator;
  35.         $this->requestStack $requestStack;
  36.     }
  37.     public function onKernelRequest(GetResponseEvent $event) {
  38.         $this->setLocale($event->getRequest());
  39.     }
  40.     public function onKernelFinishRequest(FinishRequestEvent $event) {
  41.         if (null === $parentRequest $this->requestStack->getParentRequest()) {
  42.             return;
  43.         }
  44.         $this->setLocale($parentRequest);
  45.     }
  46.     public static function getSubscribedEvents() {
  47.         return [
  48.             // must be registered after the Locale listener
  49.             KernelEvents::REQUEST => [['onKernelRequest'10]],
  50.             KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest'0]],
  51.         ];
  52.     }
  53.     private function setLocale(Request $request) {
  54.         try {
  55.             $this->translator->setLocale($request->getLocale());
  56.         } catch (\InvalidArgumentException $e) {
  57.             $this->translator->setLocale($request->getDefaultLocale());
  58.         }
  59.     }
  60. }