<?php declare(strict_types=1);
namespace PPAdmin\EventSubscriber;
use JetBrains\PhpStorm\ArrayShape;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Allows overriding UI language by manual language switch
* @link https://symfony.com/doc/current/session/locale_sticky_session.html
*/
class LocaleSubscriber implements EventSubscriberInterface
{
const LOCALE_KEY = '_locale';
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (
!$request->hasPreviousSession() ||
!$event->isMainRequest()
) {
return;
}
$session = $request->getSession();
if ($locale = $request->get(self::LOCALE_KEY)) {
$session->set(self::LOCALE_KEY, $locale);
$response = new RedirectResponse($request->getPathInfo());
$event->setResponse($response);
return;
}
$locale = $session->get(self::LOCALE_KEY);
if($locale){
$request->setLocale($locale);
}
}
#[ArrayShape([KernelEvents::REQUEST => "array[]"])]
public static function getSubscribedEvents(): array
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}