src/EventSubscriber/LocaleFromQuerySubscriber.php line 28
<?phpdeclare(strict_types=1);namespace App\EventSubscriber;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;use Symfony\Component\HttpKernel\KernelEvents;use Symfony\Component\Translation\LocaleSwitcher;/*** Override the locale selection using a query parameter named `locale`.* This should have priority over the "Accept-Language" header.* We only switch to locales enabled in config/packages/translation.yaml** @noinspection PhpUnused*/class LocaleFromQuerySubscriber implements EventSubscriberInterface{public function __construct(private LocaleSwitcher $localeSwitcher,private array $enabledLocales,) {// 🤖}public function onControllerArguments(ControllerArgumentsEvent $event): void{$locale = $event->getRequest()->get("locale", "");// Symfony expects underscore instead of dash in locale// Even though we're only using two letter codes for now, feels OK to leave this.// Who knows, swiss has quite a lot of skiing, right?$locale = str_replace('-', '_', $locale);// We only switch the locale if it's enabled in config/packages/translation.yamlif ($locale !== "" && \in_array($locale, $this->enabledLocales)) {$this->localeSwitcher->setLocale($locale);$event->getRequest()->setLocale($locale);}}public static function getSubscribedEvents(): array{return [// Do not use kernel.request here, it's too early in the pipeline.KernelEvents::CONTROLLER_ARGUMENTS => 'onControllerArguments',];}}