<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class LocaleSubscriber implements EventSubscriberInterface
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::REQUEST => ['redirectToLocalizedHomepage', 110],
];
}
public function redirectToLocalizedHomepage(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
if ($event->getRequest()->getPathInfo() !== '/') {
return;
}
$acceptLanguages = $event->getRequest()->headers->get('Accept-Language');
$locales = explode('|', $this->params->get('sinapse.locales'));
if (empty($acceptLanguages) || empty($locales)) {
return;
}
$negotiator = new \Negotiation\LanguageNegotiator();
$bestLanguage = $negotiator->getBest($acceptLanguages, $locales);
if ($bestLanguage) {
$locale = $bestLanguage->getType();
} else {
$locale = 'en';
}
$event->getRequest()->setLocale($locale);
}
}