1

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',
        ];
    }
}
yivi
  • 42,438
  • 18
  • 116
  • 138
mardon
  • 1,065
  • 1
  • 11
  • 29

1 Answers1

1

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), or Symfony\Component\Security\Core\User\User if 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:

public function onInteractiveLogin(InteractiveLoginEvent $event)
{
   $user = $event->getAuthenticationToken()->getUser();

   if ( $user instanceof App\Entity\User && null !== $user->getLocale()) {
      $this->session->set('_locale', $user->getLocale());
   }
}
yivi
  • 42,438
  • 18
  • 116
  • 138
  • This code is not function. I try this `if ($user instanceof UserInterface && null !== $user->getLocale()) { $this->session->set('_locale', $user->getLocale()); }` but this also is not function – mardon Jul 18 '21 at 17:45
  • What do you mean “it doesn’t function “? What error do you get? Are you importing the class? Your version wouldn’t work, since both classes implement `UserInterface` – yivi Jul 18 '21 at 17:52
  • Still same error `Attempted to call an undefined method named "getLocale" of class "Symfony\Component\Security\Core\User\User"`. – mardon Jul 18 '21 at 17:55
  • What version of Symfony are you on? Looks like you are on Symfony < 5.3 – yivi Jul 18 '21 at 18:03
  • I am using Symfony 4.4 and the edited code run ok. – mardon Jul 18 '21 at 18:21