<?php
namespace App\EventSubscriber;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class LanguageSubscriber implements EventSubscriberInterface
{
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
// Get the selected language from the session or request parameters
$language = $request->getSession()->get('_locale') ?? $request->getLocale();
// Set the language for the translator
$this->translator->setLocale($language);
}
public static function getSubscribedEvents()
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}