src/EventSubscriber/LoginSubscriber.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Loginhistory;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. class LoginSubscriber implements EventSubscriberInterface
  9. {
  10.     private $em;
  11.     private $requestStack;
  12.     public function __construct(EntityManagerInterface $emRequestStack $requestStack)
  13.     {
  14.         $this->em $em;
  15.         $this->requestStack $requestStack;
  16.     }
  17.     public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
  18.     {
  19.         $user $event->getAuthenticationToken()->getUser();
  20.         if (!is_object($user)) {
  21.             return;
  22.         }
  23.         $request $this->requestStack->getCurrentRequest();
  24.         $ip null;
  25.         if ($request !== null) {
  26.             $ip $request->getClientIp();
  27.         }
  28.         $login = new Loginhistory();
  29.         $login->setLogintime(new \DateTime());
  30.         $login->setUsername($user->getUsername());
  31.         $login->setUserid((string)$user->getId());
  32.         $login->setUserip($ip);
  33.         $this->em->persist($login);
  34.         $this->em->flush();
  35.     }
  36.     public static function getSubscribedEvents()
  37.     {
  38.         return [
  39.             'security.interactive_login' => 'onSecurityInteractiveLogin',
  40.         ];
  41.     }
  42. }