I began to build my first web application with symfony. In this app I got user management with authentification and multilanguage. In the user database tabel is a lang column for each user. I got the changing of the default language for the app by changing it through a _GET parameter and also by the login by the database value running. Now I want to change the value in the database automatically by switching the language through the URL _GET parameter in the EventSubscriber. Unfortunately I got no idea how to get the user entity in my 'onKernelRequest' function to save the selecte language in the database. All the logic of changing the language is done in the following code:
<?php
namespace App\EventSubscriber;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $allowedLangs;
private $session;
public function __construct(SessionInterface $session, $defaultLocale = 'de')
{
$this->defaultLocale = $defaultLocale;
$this->allowedLangs = ['de', 'en'];
$this->session = $session;
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if (null !== $user->getLocale()) {
$this->session->set('_locale', $user->getLocale());
}
}
public function onKernelRequest(GetResponseEvent $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')) {
$request->getSession()->set('_locale', $locale);
} elseif(array_key_exists('_locale', $_GET) && array_search($_GET['_locale'], $this->allowedLangs) !== FALSE) {
$request->setLocale($_GET['_locale']);
$request->getSession()->set('_locale', $_GET['_locale']);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before (i.e. with a higher priority than) the default Locale listener
SecurityEvents::INTERACTIVE_LOGIN => array(array('onInteractiveLogin', 15)),
KernelEvents::REQUEST => array(array('onKernelRequest', 20)),
);
}
}
Thanks in advance Peter