<?php
namespace App\EventSubscribers\Login;
use App\Entity\User;
use App\Repository\UserRepository;
use DateTimeImmutable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Throwable;
class LastLoginTimeOnLoginSubscriber implements EventSubscriberInterface
{
/** @var \App\Repository\UserRepository */
private UserRepository $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* @param InteractiveLoginEvent $event
* @throws Throwable
*/
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
try {
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User) {
$user->setLastLoginTime(new DateTimeImmutable());
$this->userRepository->update($user);
}
} catch (Throwable $t) {
throw $t;
}
}
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => ["onInteractiveLogin", 100],
];
}
}