]> Raphaël G. Git Repositories - packbundle/blob - Subscriber/FacebookSubscriber.php
Rename routes config to match new bundle alias
[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 /*
24 * Inject router interface and locales
25 *
26 * @param RouterInterface $router The router instance
27 * @param array $locales The supported locales
28 */
29 public function __construct(protected RouterInterface $router, protected array $locales) {
30 }
31
32 /**
33 * Change locale for request with ?fb_locale=xx
34 *
35 * @param RequestEvent The request event
36 */
37 public function onKernelRequest(RequestEvent $event): void {
38 //Without main request
39 if (!$event->isMainRequest()) {
40 return;
41 }
42
43 //Retrieve request
44 $request = $event->getRequest();
45
46 //Check for facebook locale
47 if (
48 $request->query->has('fb_locale') &&
49 in_array($locale = $request->query->get('fb_locale'), $this->locales)
50 ) {
51 //Set locale
52 $request->setLocale($locale);
53
54 //Set default locale
55 $request->setDefaultLocale($locale);
56
57 //Get router context
58 $context = $this->router->getContext();
59
60 //Set context locale
61 $context->setParameter('_locale', $locale);
62
63 //Set back router context
64 $this->router->setContext($context);
65 }
66 }
67
68 /**
69 * Get subscribed events
70 *
71 * @return array The subscribed events
72 */
73 public static function getSubscribedEvents(): array {
74 return [
75 // must be registered before the default locale listener
76 KernelEvents::REQUEST => [['onKernelRequest', 10]]
77 ];
78 }
79 }