]> Raphaƫl G. Git Repositories - airbundle/blob - EventSubscriber/LocaleSubscriber.php
Add weather and slot glyphs
[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 //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(
39 //Current route
40 $request->get('_route'),
41 //Force preferred locale
42 ['_locale' => $preferred]+$request->get('_route_params')
43 );
44
45 //Regenerate route with preferred locale
46 $event->setResponse(new RedirectResponse($uri, 302));
47
48 //End process
49 return;
50 }
51 }
52 }
53
54 public static function getSubscribedEvents() {
55 return [
56 // must be registered before the default locale listener
57 KernelEvents::REQUEST => [['onKernelRequest', 10]]
58 ];
59 }
60 }