<?php
namespace App\Locale;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleEventSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly LocaleSelector $localeSelector)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 10],
],
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
if (!$this->localeSelector->shouldShowLanguagePopin()) {
return;
}
/** @var Request $request */
$request = $event->getRequest();
if ($request->get(LocaleSelector::LOCALE_SELECT_URL_KEY, null)) {
$this->localeSelector->setMustShowLanguagePopin(false);
$url = rtrim((string) preg_replace(
'#setUserLocale=[^&]*#',
'',
$request->getUri()
), '?');
$event->setResponse(new RedirectResponse($url));
}
}
}