<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Translation\TranslatorInterface;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $translatorInterface;
private $managedLocales;
public function __construct($defaultLocale = 'en', $managedLocales, TranslatorInterface $translatorInterface)
{
$this->defaultLocale = $defaultLocale;
$this->managedLocales = $managedLocales;
$this->translatorInterface = $translatorInterface;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
// if (!$request->hasPreviousSession()) {
// return;
// }
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
$sessionLocale = $request->getSession()->get('_locale');
if (!$sessionLocale) {
$browserLocale = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : null;
$sessionLocale = (($browserLocale and in_array($browserLocale, $this->managedLocales)) ? $browserLocale : $this->defaultLocale);
}
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($sessionLocale);
$this->translatorInterface->setLocale($sessionLocale);
}
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}