src/EventListener/LanguageListener.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Customer;
  4. use App\Repository\CustomerRepository;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. class LanguageListener implements EventSubscriberInterface
  10. {
  11.     private $tokenStorage;
  12.     private $customerRepository;
  13.     public function __construct(TokenStorageInterface $tokenStorageCustomerRepository $customerRepository)
  14.     {
  15.         $this->tokenStorage       $tokenStorage;
  16.         $this->customerRepository $customerRepository;
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         $request  $event->getRequest();
  21.         $customer $this->getCustomer($request->get('id'));
  22.         if ($customer && $language $customer->getLanguage()) {
  23.             $request->setLocale($language);
  24.         }
  25.     }
  26.     /**
  27.      * @return mixed[]
  28.      */
  29.     public static function getSubscribedEvents()
  30.     {
  31.         return [
  32.             KernelEvents::REQUEST => 'onKernelRequest',
  33.         ];
  34.     }
  35.     /**
  36.      * Returns the customer if the $customerId is valid or the user is authenticated and has a valid token.
  37.      */
  38.     private function getCustomer($customerId): ?Customer
  39.     {
  40.         if ($customerId && is_int($customerId)) {
  41.             return $this->customerRepository->find($customerId);
  42.         }
  43.         if ($token $this->tokenStorage->getToken()) {
  44.             return $token->getUser();
  45.         }
  46.         return null;
  47.     }
  48. }