src/EventSubscribers/Login/LastLoginTimeOnLoginSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscribers\Login;
  3. use App\Entity\User;
  4. use App\Repository\UserRepository;
  5. use DateTimeImmutable;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  8. use Symfony\Component\Security\Http\SecurityEvents;
  9. use Throwable;
  10. class LastLoginTimeOnLoginSubscriber implements EventSubscriberInterface
  11. {
  12.     /** @var \App\Repository\UserRepository */
  13.     private UserRepository $userRepository;
  14.     public function __construct(UserRepository $userRepository)
  15.     {
  16.         $this->userRepository $userRepository;
  17.     }
  18.     /**
  19.      * @param InteractiveLoginEvent $event
  20.      * @throws Throwable
  21.      */
  22.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  23.     {
  24.         try {
  25.             $user $event->getAuthenticationToken()->getUser();
  26.             if ($user instanceof User) {
  27.                 $user->setLastLoginTime(new DateTimeImmutable());
  28.                 $this->userRepository->update($user);
  29.             }
  30.         } catch (Throwable $t) {
  31.             throw $t;
  32.         }
  33.     }
  34.     public static function getSubscribedEvents(): array
  35.     {
  36.         return [
  37.             SecurityEvents::INTERACTIVE_LOGIN => ["onInteractiveLogin"100],
  38.         ];
  39.     }
  40. }