src/EventSubscriber/LocaleSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/LocaleSubscriber.php
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Twig\Environment;
  8. class LocaleSubscriber implements EventSubscriberInterface
  9. {
  10.     private string $defaultLocale;
  11.     private $twig;
  12.     public function __construct(Environment $twigstring $defaultLocale 'fr')
  13.     {
  14.         $this->defaultLocale $defaultLocale;
  15.         $this->twig $twig;
  16.     }
  17.     public function onKernelRequest(RequestEvent $event)
  18.     {
  19.         $request $event->getRequest();
  20.         if (!$request->hasPreviousSession()) {
  21.             return;
  22.         }
  23.         // try to see if the locale has been set as a _locale routing parameter
  24.         if ($locale $request->attributes->get('_locale')) {
  25.             $request->getSession()->set('_locale'$locale);
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.             $locale $request->getSession()->get('_locale'$this->defaultLocale);
  29.             $request->setLocale($locale);
  30.         }
  31.         // setup Twig config for date and Timezone
  32.         $this->setTwigConfig ($locale);
  33.     }
  34.     public static function getSubscribedEvents()
  35.     {
  36.         return [
  37.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  38.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  39.         ];
  40.     }
  41.     public function setTwigConfig (string $locale) {
  42.         if ($locale == 'fr') {
  43.             $this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('d/m/Y''%d days');
  44.             $this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Europe/Paris');
  45.         }
  46.     }
  47. }