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\HttpKernel\Event\GetResponseEvent;
15 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
16 use Symfony\Component\HttpKernel\KernelEvents;
17 use Symfony\Component\HttpFoundation\RequestStack;
18 use Symfony\Component\HttpFoundation\Request;
19 use Symfony\Component\Routing\RequestContextAwareInterface;
20 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
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;
36 * @param RequestStack $requestStack A RequestStack instance
37 * @param string $defaultLocale The default locale
38 * @param RequestContextAwareInterface|null $router The router
40 public function __construct(RequestStack $requestStack, $defaultLocale = 'en', RequestContextAwareInterface $router = null)
42 $this->defaultLocale = $defaultLocale;
43 $this->requestStack = $requestStack;
44 $this->router = $router;
47 public function onKernelRequest(GetResponseEvent $event)
49 $request = $event->getRequest();
50 $request->setDefaultLocale($this->defaultLocale);
52 $this->setLocale($request);
53 $this->setRouterContext($request);
56 public function onKernelFinishRequest(FinishRequestEvent $event)
58 if (null !== $parentRequest = $this->requestStack->getParentRequest()) {
59 $this->setRouterContext($parentRequest);
63 private function setLocale(Request $request)
65 if ($locale = $request->attributes->get('_locale')) {
66 $request->setLocale($locale);
70 private function setRouterContext(Request $request)
72 if (null !== $this->router) {
73 $this->router->getContext()->setParameter('_locale', $request->getLocale());
77 public static function getSubscribedEvents()
80 // must be registered after the Router to have access to the _locale
81 KernelEvents::REQUEST => array(array('onKernelRequest', 16)),
82 KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),