]> Raphaël G. Git Repositories - packbundle/blob - Subscriber/FacebookSubscriber.php
Add facebook subscriber that change locale on demand
[packbundle] / Subscriber / FacebookSubscriber.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle\Subscriber;
13
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15 use Symfony\Component\HttpKernel\Event\RequestEvent;
16 use Symfony\Component\HttpKernel\KernelEvents;
17 use Symfony\Component\Routing\RouterInterface;
18
19 /**
20 * {@inheritdoc}
21 */
22 class FacebookSubscriber implements EventSubscriberInterface {
23 ///Supported locales array
24 private $locales;
25
26 ///Router instance
27 private $router;
28
29 /*
30 * Inject router interface and locales
31 *
32 * @param RouterInterface $router The router instance
33 * @param array $locales The supported locales
34 */
35 public function __construct(RouterInterface $router, array $locales) {
36 //Set locales
37 $this->locales = $locales;
38
39 //Set router
40 $this->router = $router;
41 }
42
43 /**
44 * Change locale for request with ?fb_locale=xx
45 *
46 * @param RequestEvent The request event
47 */
48 public function onKernelRequest(RequestEvent $event): void {
49 //Without main request
50 if (!$event->isMainRequest()) {
51 return;
52 }
53
54 //Retrieve request
55 $request = $event->getRequest();
56
57 //Check for facebook locale
58 if (
59 $request->query->has('fb_locale') &&
60 in_array($locale = $request->query->get('fb_locale'), $this->locales)
61 ) {
62 //Set locale
63 $request->setLocale($locale);
64
65 //Set default locale
66 $request->setDefaultLocale($locale);
67
68 //Get router context
69 $context = $this->router->getContext();
70
71 //Set context locale
72 $context->setParameter('_locale', $locale);
73
74 //Set back router context
75 $this->router->setContext($context);
76 }
77 }
78
79 /**
80 * Get subscribed events
81 *
82 * @return array The subscribed events
83 */
84 public static function getSubscribedEvents(): array {
85 return [
86 // must be registered before the default locale listener
87 KernelEvents::REQUEST => [['onKernelRequest', 10]]
88 ];
89 }
90 }