6967ad0298b59aa8955d4b894d05f69727cda1fa
[yaffs-website] / vendor / symfony / http-kernel / EventListener / TranslatorListener.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\HttpKernel\EventListener;
13
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
17 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
18 use Symfony\Component\HttpKernel\KernelEvents;
19 use Symfony\Component\HttpFoundation\RequestStack;
20 use Symfony\Component\Translation\TranslatorInterface;
21
22 /**
23  * Synchronizes the locale between the request and the translator.
24  *
25  * @author Fabien Potencier <fabien@symfony.com>
26  */
27 class TranslatorListener implements EventSubscriberInterface
28 {
29     private $translator;
30     private $requestStack;
31
32     public function __construct(TranslatorInterface $translator, RequestStack $requestStack)
33     {
34         $this->translator = $translator;
35         $this->requestStack = $requestStack;
36     }
37
38     public function onKernelRequest(GetResponseEvent $event)
39     {
40         $this->setLocale($event->getRequest());
41     }
42
43     public function onKernelFinishRequest(FinishRequestEvent $event)
44     {
45         if (null === $parentRequest = $this->requestStack->getParentRequest()) {
46             return;
47         }
48
49         $this->setLocale($parentRequest);
50     }
51
52     public static function getSubscribedEvents()
53     {
54         return array(
55             // must be registered after the Locale listener
56             KernelEvents::REQUEST => array(array('onKernelRequest', 10)),
57             KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
58         );
59     }
60
61     private function setLocale(Request $request)
62     {
63         try {
64             $this->translator->setLocale($request->getLocale());
65         } catch (\InvalidArgumentException $e) {
66             $this->translator->setLocale($request->getDefaultLocale());
67         }
68     }
69 }