src/Security/LocalePreservingLogoutHandler.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Http\Event\LogoutEvent;
  8. /**
  9.  * Symfony's session logout listener invalidates the session (wiping the
  10.  * "_locale" the user picked) before dispatching LogoutEvent to subscribers
  11.  * like this one.
  12.  *
  13.  * $token is still the authenticated one here (LogoutListener clears
  14.  * TokenStorage only after dispatching the event), but the request's own
  15.  * locale is not - LocaleListener runs at a lower kernel.request priority
  16.  * than the security firewall, so it hasn't executed yet for this request
  17.  * and Request::getLocale() is still just the untouched framework default.
  18.  * Re-derive the effective locale from the token directly, mirroring
  19.  * LocaleListener's own authenticated-user resolution, so the locale the
  20.  * user was actually browsing in survives into the anonymous session.
  21.  */
  22. class LocalePreservingLogoutHandler implements EventSubscriberInterface
  23. {
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [LogoutEvent::class => 'onLogout'];
  27.     }
  28.     public function onLogout(LogoutEvent $logoutEvent): void
  29.     {
  30.         $token $logoutEvent->getToken();
  31.         if (!$token) {
  32.             return;
  33.         }
  34.         $request $logoutEvent->getRequest();
  35.         $request->getSession()->set('_locale'$this->resolveLocale($token$request));
  36.     }
  37.     private function resolveLocale(TokenInterface $tokenRequest $request): string
  38.     {
  39.         $user $token->getUser();
  40.         if (!$user instanceof User) {
  41.             return $request->getSession()->get('_locale'$request->getLocale());
  42.         }
  43.         if (!$company $user->getCompany()) {
  44.             return $request->getSession()->get('_locale'$request->getLocale());
  45.         }
  46.         return $company->getLanguage();
  47.     }
  48. }