src/EventListener/LoginSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. // src/EventListener/LoginSubscriber.php
  3. namespace App\EventListener;
  4. use App\Entity\User as AppUser;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. // https://symfonycasts.com/screencast/deep-dive/event-listener
  11. // https://rihards.com/2018/symfony-login-event-listener/
  12. class LoginSubscriber implements EventSubscriberInterface
  13. {
  14.     private $em;
  15.     public function __construct(EntityManagerInterface $em)
  16.     {
  17.          $this->em $em;
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [LoginSuccessEvent::class => 'onLogin'];
  22.     }
  23.     public function onLogin(LoginSuccessEvent $event): void
  24.     {
  25.         // get the security token of the session that is about to be logged out
  26.         $user $event->getUser();
  27.         
  28.         if (!$user instanceof AppUser) {
  29.             return;
  30.         }
  31.         // Update your field here.
  32.         $user->setLastLogin(new \DateTime());
  33.         // Persist the data to database.
  34.         $this->em->persist($user);
  35.         $this->em->flush();
  36.     }
  37. }