<?php
/**
* @license SILK SOFTWARE HOUSE SP Z O O
*/
namespace App\EventSubscriber;
use App\Repository\UserSettingRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* Class LocaleSubscriber.
*/
class LocaleSubscriber implements EventSubscriberInterface
{
/**
* Repository.
*
* @var UserSettingRepository
*/
private $repository;
/**
* Default locale.
*
* @var string
*/
private $defaultLocale = 'en';
/**
* LocaleSubscriber constructor.
*
* @param UserSettingRepository $repository
* @param string $defaultLocale
*/
public function __construct(UserSettingRepository $repository, $defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
$this->repository = $repository;
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if (!($locale = $request->attributes->get('_locale'))) {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
/**
* On security interactive login.
*
* @param InteractiveLoginEvent $event
*/
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
if (!$event->getAuthenticationToken() || !$event->getAuthenticationToken()->getUser()) {
return;
}
$user = $event->getAuthenticationToken()->getUser();
if ($settings = $this->repository->getOrCreateForUser($user)) {
$event->getRequest()->getSession()->set('_locale', $settings->getLanguage());
}
}
/**
* Get subscribed events.
*
* @return array
*/
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
SecurityEvents::INTERACTIVE_LOGIN => [['onSecurityInteractiveLogin', 18]],
];
}
}