src/EventSubscriber/LocaleFromQuerySubscriber.php line 28

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\Translation\LocaleSwitcher;
  8. /**
  9.  * Override the locale selection using a query parameter named `locale`.
  10.  * This should have priority over the "Accept-Language" header.
  11.  * We only switch to locales enabled in config/packages/translation.yaml
  12.  *
  13.  * @noinspection PhpUnused
  14.  */
  15. class LocaleFromQuerySubscriber implements EventSubscriberInterface
  16. {
  17.     public function __construct(
  18.         private LocaleSwitcher $localeSwitcher,
  19.         private array $enabledLocales,
  20.     ) {
  21.         // ðŸ¤–
  22.     }
  23.     public function onControllerArguments(ControllerArgumentsEvent $event): void
  24.     {
  25.         $locale $event->getRequest()->get("locale""");
  26.         // Symfony expects underscore instead of dash in locale
  27.         // Even though we're only using two letter codes for now, feels OK to leave this.
  28.         // Who knows, swiss has quite a lot of skiing, right?
  29.         $locale str_replace('-''_'$locale);
  30.         // We only switch the locale if it's enabled in config/packages/translation.yaml
  31.         if ($locale !== "" && \in_array($locale$this->enabledLocales)) {
  32.             $this->localeSwitcher->setLocale($locale);
  33.             $event->getRequest()->setLocale($locale);
  34.         }
  35.     }
  36.     public static function getSubscribedEvents(): array
  37.     {
  38.         return [
  39.             // Do not use kernel.request here, it's too early in the pipeline.
  40.             KernelEvents::CONTROLLER_ARGUMENTS => 'onControllerArguments',
  41.         ];
  42.     }
  43. }