<?php
namespace App\EventListener;
use App\Entity\Customer;
use App\Repository\CustomerRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class LanguageListener implements EventSubscriberInterface
{
private $tokenStorage;
private $customerRepository;
public function __construct(TokenStorageInterface $tokenStorage, CustomerRepository $customerRepository)
{
$this->tokenStorage = $tokenStorage;
$this->customerRepository = $customerRepository;
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$customer = $this->getCustomer($request->get('id'));
if ($customer && $language = $customer->getLanguage()) {
$request->setLocale($language);
}
}
/**
* @return mixed[]
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
/**
* Returns the customer if the $customerId is valid or the user is authenticated and has a valid token.
*/
private function getCustomer($customerId): ?Customer
{
if ($customerId && is_int($customerId)) {
return $this->customerRepository->find($customerId);
}
if ($token = $this->tokenStorage->getToken()) {
return $token->getUser();
}
return null;
}
}