<?php
namespace App\EventSubscriber;
use App\Service\ParameterService;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class HttpRequestSubscriber implements EventSubscriberInterface
{
private string $defaultLocale;
public function __construct(ParameterBagInterface $parameterBag,
private readonly ParameterService $parameterService
)
{
$this->defaultLocale = $parameterBag->get('app.default_locale');
}
public function onKernelRequest(RequestEvent $event) : void
{
$request = $event->getRequest();
// Check if session exists
// if (!$request->hasPreviousSession()) {
// return;
// }
// Check if the session already has a locale
$session = $request->getSession();
if ($session->has('_locale')) {
$locale = $session->get('_locale');
} else {
// Determine the locale (e.g., from a cookie or default)
$locale = $request->cookies->get('user_locale', $this->defaultLocale);
$session->set('_locale', $locale);
}
// Set the locale in the request
$request->setLocale($locale);
if(!$session->has('userCurrency')){
$session->set('userCurrency', $this->parameterService->getReferenceCurrency());
}
}
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]],
];
}
}