Well thanks to Elnur I decided to go back to my jms_i18n solution (see comments in Elnur's answer), and I found this question that helped me build my own solution. So I switched from an EventSubscriber extended class to a simple "unextended" class of my own. Here is the working code:
<?php
//src/myApp/MainBundle/EventListener/LocaleListener.php
namespace myApp\MainBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Cookie;
class LocaleListener
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
if ($request->getRequestFormat() !== 'html') {
return;
}
$token = $this->container->get('security.context')->getToken();
if (is_object($token)) {
$user = $token->getUser();
if (is_object($user)) {
$userlocale = $user->getLocale();
if ($userlocale && $userlocale != $request->get('_locale')) {
$parmArray = $request->get('_route_params');
$parmArray['_locale'] = $userlocale;
$redirectResponse = new RedirectResponse( $this->container->get('router')->generate($request->get('_route'), $parmArray) );
$redirectResponse->headers->setCookie( new Cookie('b_locale', $userlocale, time() + 2592000) );
$event->setResponse( $redirectResponse );
}
}
}
}
}
And here is how to register it in services :
# app/config/config.yml
services:
myapp_main.locale_listener:
class: myApp\MainBundle\EventListener\LocaleListener
arguments: ["@service_container"]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Many thanks to Elnur for changing my mind.