1// src/EventSubscriber/LocaleSubscriber.php
2namespace App\EventSubscriber;
3
4use Symfony\Component\EventDispatcher\EventSubscriberInterface;
5use Symfony\Component\HttpKernel\Event\RequestEvent;
6use Symfony\Component\HttpKernel\KernelEvents;
7
8class LocaleSubscriber implements EventSubscriberInterface
9{
10 private $defaultLocale;
11
12 public function __construct(string $defaultLocale = 'en')
13 {
14 $this->defaultLocale = $defaultLocale;
15 }
16
17 public function onKernelRequest(RequestEvent $event)
18 {
19 $request = $event->getRequest();
20 if (!$request->hasPreviousSession()) {
21 return;
22 }
23
24 // try to see if the locale has been set as a _locale routing parameter
25 if ($locale = $request->attributes->get('_locale')) {
26 $request->getSession()->set('_locale', $locale);
27 } else {
28 // if no explicit locale has been set on this request, use one from the session
29 $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
30 }
31 }
32
33 public static function getSubscribedEvents()
34 {
35 return [
36 // must be registered before (i.e. with a higher priority than) the default Locale listener
37 KernelEvents::REQUEST => [['onKernelRequest', 20]],
38 ];
39 }
40}
41