<?php
namespace Aqarmap\Bundle\UserBundle\EventListener;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
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 LocaleEventSubscriber implements EventSubscriberInterface
{
private TokenStorageInterface $tokenStorage;
private EntityManagerInterface $em;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
{
$this->tokenStorage = $tokenStorage;
$this->em = $em;
}
public function onKernelRequest(RequestEvent $event): void
{
if (null === $this->tokenStorage->getToken()) {
return;
}
$user = $this->tokenStorage->getToken()->getUser();
$locale = $event->getRequest()->attributes->get('_locale', 'ar');
if ($user instanceof User && $user->getLanguage() !== $locale) {
$user->setLanguage($locale);
try {
$this->em->persist($user);
$this->em->flush($user);
} catch (\Exception $exception) {
return;
}
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
}