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\Routing\RequestContextAwareInterface;
23 * Initializes the locale based on the current request.
25 * @author Fabien Potencier <fabien@symfony.com>
27 class LocaleListener implements EventSubscriberInterface
30 private $defaultLocale;
31 private $requestStack;
34 * @param RequestStack $requestStack A RequestStack instance
35 * @param string $defaultLocale The default locale
36 * @param RequestContextAwareInterface|null $router The router
38 public function __construct(RequestStack $requestStack, $defaultLocale = 'en', RequestContextAwareInterface $router = null)
40 $this->defaultLocale = $defaultLocale;
41 $this->requestStack = $requestStack;
42 $this->router = $router;
45 public function onKernelRequest(GetResponseEvent $event)
47 $request = $event->getRequest();
48 $request->setDefaultLocale($this->defaultLocale);
50 $this->setLocale($request);
51 $this->setRouterContext($request);
54 public function onKernelFinishRequest(FinishRequestEvent $event)
56 if (null !== $parentRequest = $this->requestStack->getParentRequest()) {
57 $this->setRouterContext($parentRequest);
61 private function setLocale(Request $request)
63 if ($locale = $request->attributes->get('_locale')) {
64 $request->setLocale($locale);
68 private function setRouterContext(Request $request)
70 if (null !== $this->router) {
71 $this->router->getContext()->setParameter('_locale', $request->getLocale());
75 public static function getSubscribedEvents()
78 // must be registered after the Router to have access to the _locale
79 KernelEvents::REQUEST => array(array('onKernelRequest', 16)),
80 KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),