src/Service/UserLocationLogger.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\AuthLog;
  4. use App\Entity\User;
  5. use DateTime;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Exception;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  10. class UserLocationLogger implements EventSubscriberInterface
  11. {
  12.     private EntityManagerInterface $entityManager;
  13.     public function __construct(EntityManagerInterface $entityManager)
  14.     {
  15.         $this->entityManager $entityManager;
  16.     }
  17.     /**
  18.      * @throws Exception
  19.      */
  20.     public function createAuthLog(LoginSuccessEvent $event)
  21.     {
  22.         /* @var User $user */
  23.         $user $event->getAuthenticatedToken()->getUser();
  24.         $ip $event->getRequest()->getClientIp();
  25.         $geoInfo = new GeoInfo($ip);
  26.         $authLog = new AuthLog();
  27.         $authLog
  28.             ->setUser($user)
  29.             ->setIp($ip)
  30.             ->setCountry($geoInfo->getCountry())
  31.             ->setVille($geoInfo->getCity())
  32.             ->setCreatedAt(new DateTime());
  33.         $this->entityManager->persist($authLog);
  34.         $this->entityManager->flush();
  35.     }
  36.     public static function getSubscribedEvents(): array
  37.     {
  38.         return [
  39.             LoginSuccessEvent::class => 'createAuthLog'
  40.         ];
  41.     }
  42. }