<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $domainLocales;
public function __construct($container, $defaultLocale = 'en')
{
$this->domainLocales = $container->getParameter('domain_locales');
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$host = $request->getHost();
$locale = $this->defaultLocale;
$domainLocale = array_search($host, $this->domainLocales);
if (!empty($domainLocale)) {
$locale = $domainLocale;
$request->setLocale($locale);
} else {
if (!$request->getSession()->has('_locale')) {
$request->getSession()->set('_locale', $this->defaultLocale);
}
// 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 {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale'));
}
}
}
public static function getSubscribedEvents(): array
{
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}