src/EventSubscriber/User/UserLoginSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\User;
  3. use App\Entity\LoginHistory;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  8. use Symfony\Component\Security\Http\SecurityEvents;
  9. class UserLoginSubscriber implements EventSubscriberInterface
  10. {
  11.     protected $entityManager;
  12.     public function __construct(
  13.         EntityManagerInterface $entityManager
  14.     ) {
  15.         $this->entityManager $entityManager;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             SecurityEvents::INTERACTIVE_LOGIN => 'onLogin',
  21.         ];
  22.     }
  23.     public function onLogin(InteractiveLoginEvent $event): void
  24.     {
  25.         $user $event->getAuthenticationToken()->getUser();
  26.         if (!$user instanceof User) {
  27.             return;
  28.         }
  29.         $history = new LoginHistory($user);
  30.         $this->entityManager->persist($history);
  31.         $this->entityManager->flush();
  32.     }
  33. }