3 namespace Rapsys\AirBundle\EventSubscriber
;
5 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
6 use Symfony\Component\HttpKernel\Event\RequestEvent
;
7 use Symfony\Component\HttpKernel\KernelEvents
;
8 use Symfony\Component\HttpFoundation\RedirectResponse
;
9 use Symfony\Component\Routing\RouterInterface
;
11 class LocaleSubscriber
implements EventSubscriberInterface
{
15 public function __construct(RouterInterface
$router, array $locales = ['en']) {
16 $this->locales
= $locales;
17 $this->router
= $router;
20 public function onKernelRequest(RequestEvent
$event) {
22 $request = $event->getRequest();
25 //XXX: people blocking cookies will be stuck to preferred language version
26 if (!$request->hasPreviousSession()) {
27 //Get preferred language
28 //XXX: default language is unused, it will return locales[0] if everything fail
29 $preferred = $request->getPreferredLanguage($this->locales
);
31 //Check if preferred language differs from current request locale
32 if ($preferred != $request->getLocale()) {
33 //Save preferred locale in session
34 $request->getSession()->set('_locale', $preferred);
36 //Generate current route with preferred language
37 //XXX: may trigger a Symfony\Component\Routing\Exception\RouteNotFoundException if route is not found for preferred locale
38 $uri = $this->router
->generate(
40 $request->get('_route'),
41 //Force preferred locale
42 ['_locale' => $preferred]+
$request->get('_route_params')
45 //Regenerate route with preferred locale
46 $event->setResponse(new RedirectResponse($uri, 302));
54 public static function getSubscribedEvents() {
56 // must be registered before the default locale listener
57 KernelEvents
::REQUEST
=> [['onKernelRequest', 10]]