<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $translator;
public function __construct(string $defaultLocale = 'en', TranslatorInterface $translator)
{
$this->defaultLocale = $defaultLocale;
$this->translator = $translator;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
$locale = $request->getSession()->get('_locale', $this->defaultLocale);
$request->setLocale($locale);
$this->translator->setLocale($locale);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}