src/EventSubscriber/UserAuthenticationSuccessSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use App\Entity\User;
  7. class UserAuthenticationSuccessSubscriber implements EventSubscriberInterface
  8. {
  9.     private $entity_manager;
  10.     public function __construct(EntityManagerInterface $entity_manager)
  11.     {
  12.         $this->entity_manager $entity_manager;
  13.     }
  14.     
  15.     public function onSecurityAuthenticationSuccess(AuthenticationSuccessEvent $event): void
  16.     {
  17.         $user $event->getAuthenticationToken()->getUser();
  18.         if ($user instanceof User)
  19.         {
  20.             $user->setLastLoginAt(new \DateTime('now', new \DateTimeZone(User::TIMEZONE)));
  21.             $this->entity_manager->persist($user);
  22.             $this->entity_manager->flush();
  23.         }
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             'security.authentication.success' => 'onSecurityAuthenticationSuccess',
  29.         ];
  30.     }
  31. }