src/EventSubscriber/LocaleSubscriber.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8.     private string $defaultLocale;
  9.     public function __construct(string $defaultLocale 'fr')
  10.     {
  11.         $this->defaultLocale $defaultLocale;
  12.     }
  13.     public function onKernelRequest(RequestEvent $event)
  14.     {
  15.         $request $event->getRequest();
  16.         if ($locale $request->headers->get('Accept-Language')) {
  17.             $request->setLocale($locale);
  18.         } else {
  19.             $request->setLocale($this->defaultLocale);
  20.         }
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  26.         ];
  27.     }
  28. }