X-Git-Url: https://git.rapsys.eu/packbundle/blobdiff_plain/004e139a1e7b0fbd2008f225a6dd4df0801c971e..f414da492f983455e1db3f9e89f8cb12a8a1ed8b:/Subscriber/FacebookSubscriber.php diff --git a/Subscriber/FacebookSubscriber.php b/Subscriber/FacebookSubscriber.php new file mode 100644 index 0000000..c87b19a --- /dev/null +++ b/Subscriber/FacebookSubscriber.php @@ -0,0 +1,90 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Rapsys\PackBundle\Subscriber; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\Event\RequestEvent; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\Routing\RouterInterface; + +/** + * {@inheritdoc} + */ +class FacebookSubscriber implements EventSubscriberInterface { + ///Supported locales array + private $locales; + + ///Router instance + private $router; + + /* + * Inject router interface and locales + * + * @param RouterInterface $router The router instance + * @param array $locales The supported locales + */ + public function __construct(RouterInterface $router, array $locales) { + //Set locales + $this->locales = $locales; + + //Set router + $this->router = $router; + } + + /** + * Change locale for request with ?fb_locale=xx + * + * @param RequestEvent The request event + */ + public function onKernelRequest(RequestEvent $event): void { + //Without main request + if (!$event->isMainRequest()) { + return; + } + + //Retrieve request + $request = $event->getRequest(); + + //Check for facebook locale + if ( + $request->query->has('fb_locale') && + in_array($locale = $request->query->get('fb_locale'), $this->locales) + ) { + //Set locale + $request->setLocale($locale); + + //Set default locale + $request->setDefaultLocale($locale); + + //Get router context + $context = $this->router->getContext(); + + //Set context locale + $context->setParameter('_locale', $locale); + + //Set back router context + $this->router->setContext($context); + } + } + + /** + * Get subscribed events + * + * @return array The subscribed events + */ + public static function getSubscribedEvents(): array { + return [ + // must be registered before the default locale listener + KernelEvents::REQUEST => [['onKernelRequest', 10]] + ]; + } +}