<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $twig;
public function __construct(string $defaultLocale = "en", Environment $twig)
{
$this->twig = $twig;
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
// return;
}
if ($locale = $request->query->get('_locale')) {
$globals = $this->twig->getGlobals();
if (in_array($locale, $globals['locales'])) {
$this->defaultLocale = $locale;
}
$request->getSession()->set('_locale', $this->defaultLocale);
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 0]],
];
}
}