<?php
namespace App\EventSubscriber;
use App\Entity\App\User;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleListenerSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $jwtEncoder;
public function __construct(
TokenStorageInterface $tokenStorage,
JWTEncoderInterface $jwtEncoder
) {
$this->tokenStorage = $tokenStorage;
$this->jwtEncoder = $jwtEncoder;
}
/**
* @param RequestEvent $event
* @throws \Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$language =explode(",",$request->headers->get("Accept-Language"))[0];
$request->setLocale($language);
/*
$token = $this->tokenStorage->getToken();
$language = [
User::LOCALE_EN,
User::LOCALE_ES
];
if(!isset($token))
return;
if($token->getUser() instanceof User && $token->getCredentials()) {
$payload = $this->jwtEncoder->decode($token->getCredentials());
if ($payload && array_key_exists('locale', $payload) && in_array($payload['locale'], $language)) {
$request->attributes->set('_locale', $payload['locale']);
$request->setLocale($payload['locale']);
}
} else if ($locale = $request->attributes->get('_locale')) {
$request->setLocale($locale);
}
*/
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 20]
];
}
}