src/EventListener/LoginHistoryListener.php line 35

  1. <?php 
  2. namespace App\EventListener;
  3. use App\Entity\LoginHistory;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  6. use Symfony\Component\Security\Http\Event\LogoutEvent;
  7. class LoginHistoryListener
  8. {
  9.     private $entityManager;
  10.     public function __construct(EntityManagerInterface $entityManager)
  11.     {
  12.         $this->entityManager $entityManager;
  13.     }
  14.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  15.     {
  16.        
  17.         // Get the user who logged in
  18.         $user $event->getAuthenticationToken()->getUser();
  19.         // Create a new LoginHistory entry
  20.         $loginHistory = new LoginHistory();
  21.         $loginHistory->setUser($user);
  22.         $loginHistory->setLoginAt(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));
  23.         // Persist the LoginHistory entry
  24.         $this->entityManager->persist($loginHistory);
  25.         $this->entityManager->flush();
  26.     }
  27.     public function onLogout(LogoutEvent $event)
  28.     {        
  29.         // Get the user who logged out
  30.         $user $event->getToken()->getUser();
  31.         // Find the most recent LoginHistory entry for the user
  32.         $loginHistory $this->entityManager->getRepository(LoginHistory::class)->findOneBy(
  33.             ['user' => $user],
  34.             ['loginAt' => 'DESC']
  35.         );
  36.         if ($loginHistory) {
  37.             // Update the Logout timestamp
  38.             $loginHistory->setLogoutAt(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));
  39.             $this->entityManager->flush();
  40.         }
  41.     }
  42. }