src/EventSubscriber/LogoutSubscriber.php line 21

Open in your IDE?
  1. <?php
  2.  
  3. namespace App\EventSubscriber;
  4.  
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. use Symfony\Component\Security\Core\Security;
  9.  
  10. class LogoutSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(private Security $security)
  13.     {
  14.        
  15.     }
  16.  
  17.     public function onKernelResponse(ResponseEvent $event): void
  18.     {
  19.         $request $event->getRequest();
  20.         $session $request->getSession();
  21.         $unauthentified $session->get('unauthentified');
  22.         if ($this->security->getUser() && isset($unauthentified)) {
  23.             $targetUrl $request->getBaseUrl()."/logout";
  24.             if ($request->getPathInfo() != "/logout") {
  25.                 $redirectUrl = new RedirectResponse($targetUrl);
  26.                 $event->setResponse($redirectUrl);
  27.             }
  28.         }
  29.     }
  30.  
  31.     public static function getSubscribedEvents(): array
  32.     {
  33.         return [
  34.             'kernel.response' => 'onKernelResponse',
  35.         ];
  36.     }
  37. }
  38.