<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class LocaleListener.
*/
class LocaleListener implements EventSubscriberInterface
{
// TODO : Récupérer valeur de la config
public const DEFAULT_LOCALE = 'fr';
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
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);
}
$request->setLocale($request->getSession()->get('_locale', self::DEFAULT_LOCALE));
// Handle Redirections
// TODO : Sécuriser pour ce domaine uniquement
$redirect = $request->query->get('redirect');
if (!empty($redirect)) {
$redirect = urldecode($redirect);
$event->setResponse(new RedirectResponse($redirect));
}
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::REQUEST => [
['onKernelRequest', 15],
],
);
}
}