]> Raphaƫl G. Git Repositories - airbundle/blob - EventSubscriber/LocaleSubscriber.php
Add dance link
[airbundle] / EventSubscriber / LocaleSubscriber.php
1 <?php
2
3 namespace Rapsys\AirBundle\EventSubscriber;
4
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;
10
11 class LocaleSubscriber implements EventSubscriberInterface {
12 private $locales;
13 private $router;
14
15 public function __construct(RouterInterface $router, array $locales = ['en']) {
16 $this->locales = $locales;
17 $this->router = $router;
18 }
19
20 public function onKernelRequest(RequestEvent $event) {
21 //Retrieve request
22 $request = $event->getRequest();
23
24 //Check for session
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);
30
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);
35
36 //Send vary header as current page locale depend on it
37 #header('Vary: accept-language');
38
39 //Set locale
40 #$request->setLocale($preferred);
41
42 //Set default locale
43 #$request->setDefaultLocale($preferred);
44
45 //Get router context
46 #$context = $this->router->getContext();
47
48 //Set context locale
49 #$context->setParameter('_locale', $preferred);
50
51 //Set back router context
52 #$this->router->setContext($context);
53
54 //End process
55 return;
56 }
57 }
58 }
59
60 public static function getSubscribedEvents() {
61 return [
62 // must be registered before the default locale listener
63 KernelEvents::REQUEST => [['onKernelRequest', 10]]
64 ];
65 }
66 }