src/EventSubscriber/LocaleListenerSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\App\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class LocaleListenerSubscriber implements EventSubscriberInterface
  10. {
  11.     private $tokenStorage;
  12.     private $jwtEncoder;
  13.     public function __construct(
  14.         TokenStorageInterface $tokenStorage,
  15.         JWTEncoderInterface $jwtEncoder
  16.     ) {
  17.         $this->tokenStorage $tokenStorage;
  18.         $this->jwtEncoder $jwtEncoder;
  19.     }
  20.     /**
  21.      * @param RequestEvent $event
  22.      * @throws \Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException
  23.      */
  24.     public function onKernelRequest(RequestEvent $event)
  25.     {
  26.         $request $event->getRequest();
  27.         $language =explode(",",$request->headers->get("Accept-Language"))[0];
  28.         $request->setLocale($language);
  29.         /*
  30.         $token = $this->tokenStorage->getToken();
  31.         $language = [
  32.           User::LOCALE_EN,
  33.           User::LOCALE_ES
  34.         ];
  35.         if(!isset($token))
  36.             return;
  37.         if($token->getUser() instanceof User && $token->getCredentials()) {
  38.             $payload = $this->jwtEncoder->decode($token->getCredentials());
  39.             if ($payload && array_key_exists('locale', $payload) && in_array($payload['locale'], $language)) {
  40.                 $request->attributes->set('_locale', $payload['locale']);
  41.                 $request->setLocale($payload['locale']);
  42.             }
  43.         } else if ($locale = $request->attributes->get('_locale')) {
  44.             $request->setLocale($locale);
  45.         }
  46.         */
  47.     }
  48.     public static function getSubscribedEvents()
  49.     {
  50.         return [
  51.             KernelEvents::REQUEST => ['onKernelRequest'20]
  52.         ];
  53.     }
  54. }