I have UserLocaleSubscriber from Symfony documentation for switch locale by user. But my admin user is stored "In memory", and the InMemoryUser class does not have the getLocale() method.
How may I run this subscriber only for user User entity. I tried isGranted() but couldn't get it to work.
class UserLocaleSubscriber implements EventSubscriberInterface
{
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if (null !== $user->getLocale()) {
$this->session->set('_locale', $user->getLocale());
}
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
];
}
}
Only apply the locale change if the user instance is not of type
Symfony\Component\Security\Core\User\InMemoryUser(if you are on Symfony 5.3), orSymfony\Component\Security\Core\User\Userif you haven't gotten to that version yet.Or better, check that the user entity you are getting is the one you expect. Let's say your user entity is
App\Entity\User: