<?php
namespace App\Event;
use App\Entity\Language;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* Stores the locale of the user in the session after the
* login. This can be used by the LocaleSubscriber afterwards.
*/
class UserLocaleSubscriber implements EventSubscriberInterface
{
private $session;
private $request_stack;
private $security;
public function __construct(EntityManagerInterface $entity_manager, RequestStack $requestStack, Security $security)
{
$this->entity_manager = $entity_manager;
$this->request_stack = $requestStack;
$this->security = $security;
}
public function onLoginSuccess(LoginSuccessEvent $event)
{
$User = $event->getUser();
$Customer = $User->getCustomer();
$Settings = $Customer->getSettings();
$customerLanguagesArray = (isset($Settings['languages'])) ? $Settings['languages'] : [];
$request = $event->getRequest();
$session = $request->getSession();
$userLocale = $this->entity_manager->getRepository(Language::class)->findOneBy(array('Code'=>$User->getLocale()));
$userLocaleId = $userLocale->getId();
if (in_array($userLocaleId, $customerLanguagesArray)) {
$defaultLanguageCode = $User->getLocale();
} else {
$defaultLanguageId = $Customer->getDefaultLanguage();
$defaultLanguage = $this->entity_manager->getRepository(Language::class)->find($defaultLanguageId);
$defaultLanguageCode = $defaultLanguage->getCode();
}
if ($defaultLanguageCode !== null) {
$request->getSession()->set('_locale', $defaultLanguageCode);
$request->setLocale($defaultLanguageCode);
$request->setDefaultLocale($defaultLanguageCode);
//dump($session);
//dd($request->getSession());
}
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
//$bag = $request->getSession()->getBag('attributes');
//dd($request->getSession()->get('_locale'));
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->getSession()->get('_locale')) {
$request->setLocale($request->getSession()->get('_locale'));
$request->setDefaultLocale($request->getSession()->get('_locale'));
} else {
$request->setLocale('en');
$request->setDefaultLocale('en');
}
}
public static function getSubscribedEvents(): ?array
{
return [
LoginSuccessEvent::class => 'onLoginSuccess',
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}