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 //Send vary header as current page locale depend on it
37 header('Vary: accept-language');
40 $request->setLocale($preferred);
43 $request->setDefaultLocale($preferred);
46 $context = $this->router
->getContext();
49 $context->setParameter('_locale', $preferred);
51 //Set back router context
52 $this->router
->setContext($context);
60 public static function getSubscribedEvents() {
62 // must be registered before the default locale listener
63 KernelEvents
::REQUEST
=> [['onKernelRequest', 10]]