<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Taken from http://symfony.com/doc/current/cookbook/session/locale_sticky_session.html
* Makes the locale "sticky", meaning that it is set at the first request
* and not each time a new request is created.
*
* Callable by service vp_auto.locale.listener
*/
class LocaleListener implements EventSubscriberInterface
{
public function __construct(private $defaultLocale = 'fr')
{
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
// if session is already set, do nothing
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 {
// 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 the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 17]],
];
}
}