4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\EventListener;
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\HttpFoundation\RequestStack;
17 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
18 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
19 use Symfony\Component\HttpKernel\KernelEvents;
20 use Symfony\Component\Translation\TranslatorInterface;
23 * Synchronizes the locale between the request and the translator.
25 * @author Fabien Potencier <fabien@symfony.com>
27 class TranslatorListener implements EventSubscriberInterface
30 private $requestStack;
32 public function __construct(TranslatorInterface $translator, RequestStack $requestStack)
34 $this->translator = $translator;
35 $this->requestStack = $requestStack;
38 public function onKernelRequest(GetResponseEvent $event)
40 $this->setLocale($event->getRequest());
43 public function onKernelFinishRequest(FinishRequestEvent $event)
45 if (null === $parentRequest = $this->requestStack->getParentRequest()) {
49 $this->setLocale($parentRequest);
52 public static function getSubscribedEvents()
55 // must be registered after the Locale listener
56 KernelEvents::REQUEST => array(array('onKernelRequest', 10)),
57 KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
61 private function setLocale(Request $request)
64 $this->translator->setLocale($request->getLocale());
65 } catch (\InvalidArgumentException $e) {
66 $this->translator->setLocale($request->getDefaultLocale());