src/EventSubscriber/HttpRequestSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Service\ParameterService;
  4. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class HttpRequestSubscriber implements EventSubscriberInterface
  9. {
  10.     private string $defaultLocale;
  11.     public function __construct(ParameterBagInterface $parameterBag,
  12.                                 private readonly ParameterService $parameterService
  13.     )
  14.     {
  15.         $this->defaultLocale $parameterBag->get('app.default_locale');
  16.     }
  17.     public function onKernelRequest(RequestEvent $event) : void
  18.     {
  19.         $request $event->getRequest();
  20.         // Check if session exists
  21. //        if (!$request->hasPreviousSession()) {
  22. //            return;
  23. //        }
  24.         // Check if the session already has a locale
  25.         $session $request->getSession();
  26.         if ($session->has('_locale')) {
  27.             $locale $session->get('_locale');
  28.         } else {
  29.             // Determine the locale (e.g., from a cookie or default)
  30.             $locale $request->cookies->get('user_locale'$this->defaultLocale);
  31.             $session->set('_locale'$locale);
  32.         }
  33.         // Set the locale in the request
  34.         $request->setLocale($locale);
  35.         if(!$session->has('userCurrency')){
  36.             $session->set('userCurrency'$this->parameterService->getReferenceCurrency());
  37.         }
  38.     }
  39.     public static function getSubscribedEvents(): array
  40.     {
  41.         return [
  42.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  43.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  44.         ];
  45.     }
  46. }