src/EventListener/LoginListener.php line 32
<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\User;
use DateTime;
use DateTimeZone;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Doctrine\ORM\EntityManagerInterface;
class LoginListener implements EventSubscriberInterface
{
public function __construct(private readonly EntityManagerInterface $em) {
}
// @codeCoverageIgnoreStart
public static function getSubscribedEvents(): array
{
return [
AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
];
}
// @codeCoverageIgnoreEnd
/**
* On authentication success, define new last login
*/
public function onAuthenticationSuccess(AuthenticationEvent $event): void
{
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User && $user->getIsEnabled()) {
$user->setLastLogin(new DateTime('now', new DateTimeZone('Europe/Paris')));
$this->em->flush();
}
}
}