<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
class LocaleSubscriber implements EventSubscriberInterface
{
private $translator;
private $session;
private $environment;
public function __construct(TranslatorInterface $translator, SessionInterface $session, Environment $environment)
{
$this->translator = $translator;
$this->session = $session;
$this->environment = $environment;
}
public function onKernelController(ControllerEvent $event)
{
$request = $event->getRequest();
$locale = $request->getSession()->get('localeSession');
$locale = $locale ?? 'fr';
$this->translator->setLocale($locale);
$this->environment->addGlobal('app_default_locale', $locale);
$GLOBALS['app_default_locale'] = $locale;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}