<?php
namespace App\EventSubscriber;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class SetLanguageSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $translator;
public function __construct(TranslatorInterface $translator, TokenStorageInterface $tokenStorage)
{
$this->translator = $translator;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::CONTROLLER => 'setLanguage',
);
}
public function setLanguage(ControllerEvent $event)
{
if (strpos($event->getRequest()->getPathInfo(), 'dashboard') !== false) {
$token = $this->tokenStorage->getToken();
if (!$token) {
return;
}
/** @var User $user */
$user = $token->getUser();
if (is_string($user)) {
return;
}
$locale = $user->getLocale();
$event->getRequest()->setLocale($locale);
$this->translator->setLocale($locale);
}
}
}