]> Raphaƫl G. Git Repositories - airbundle/blob - EventSubscriber/LocaleSubscriber.php
29417a726e0222d4fbd8cd78d81d9501dff7acaf
[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 //Generate current route with preferred language
55 //XXX: may trigger a Symfony\Component\Routing\Exception\RouteNotFoundException if route is not found for preferred locale
56 /*$uri = $this->router->generate(
57 //Current route
58 $request->get('_route'),
59 //Force preferred locale
60 ['_locale' => $preferred]+$request->get('_route_params')
61 );
62
63 //Regenerate route with preferred locale
64 $event->setResponse(new RedirectResponse($uri, 302));*/
65
66 //End process
67 return;
68 }
69 }
70 }
71
72 public static function getSubscribedEvents() {
73 return [
74 // must be registered before the default locale listener
75 KernelEvents::REQUEST => [['onKernelRequest', 10]]
76 ];
77 }
78 }