src/EventListener/LoginListener.php line 32

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventListener;
  4. use App\Entity\User;
  5. use DateTime;
  6. use DateTimeZone;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Security\Core\AuthenticationEvents;
  9. use Symfony\Component\Security\Core\Event\AuthenticationEvent;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. class LoginListener implements EventSubscriberInterface
  12. {
  13.     public function __construct(private readonly EntityManagerInterface $em) {
  14.     }
  15.     // @codeCoverageIgnoreStart
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
  20.         ];
  21.     }
  22.     // @codeCoverageIgnoreEnd
  23.     /**
  24.      * On authentication success, define new last login
  25.      */
  26.     public function onAuthenticationSuccess(AuthenticationEvent $event): void
  27.     {
  28.         /** @var User $user */
  29.         $user $event->getAuthenticationToken()->getUser();
  30.         if ($user instanceof User && $user->getIsEnabled()) {
  31.             $user->setLastLogin(new DateTime('now', new DateTimeZone('Europe/Paris')));
  32.             $this->em->flush();
  33.         }
  34.     }
  35. }