src/EventSubscriber/LogoutSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Vetoadom\SessionLog;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Component\Security\Http\Event\LogoutEvent;
  9. class LogoutSubscriber implements EventSubscriberInterface
  10. {
  11.     private $requestStack;
  12.     private $vetoadomEntityManager;
  13.     public function __construct(
  14.         RequestStack $requestStack,
  15.         EntityManagerInterface $vetoadomEntityManager
  16.     ) {
  17.         $this->requestStack $requestStack;
  18.         $this->vetoadomEntityManager $vetoadomEntityManager;
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             LogoutEvent::class => 'onLogoutEvent',
  24.         ];
  25.     }
  26.     /**
  27.      * @param LogoutEvent $event
  28.      */
  29.     public function onLogoutEvent(LogoutEvent $event)
  30.     {
  31.         $token $event->getToken();
  32.         if (null === $token) {
  33.             return;
  34.         }
  35.         $user $token->getUser();
  36.         if ($user instanceof UserInterface) {
  37.             # log session time
  38.             $sessionLog $this->vetoadomEntityManager->getRepository(SessionLog::class)->findOneBy(['userId' => $user->getId()],['id' => 'DESC']);
  39.             if ($sessionLog) {
  40.                 $sessionLog->setDateFin(new \DateTime());
  41.                 $this->vetoadomEntityManager->flush();
  42.             }
  43.             # kill session
  44.             $this->requestStack->getSession()->invalidate();
  45.         }
  46.     }
  47. }