<?php
namespace App\EventSubscriber;
use App\Entity\SonataAdminUser;
use App\Entity\PressSite\AccountManager;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
class UserActivitySubscriber implements EventSubscriberInterface
{
private $em;
private $security;
public function __construct(EntityManagerInterface $em, Security $security)
{
$this->em = $em;
$this->security = $security;
}
public function onTerminate(TerminateEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
/** @var SonataAdminUser $user */
if ((!$user = $this->security->getUser()) || $user instanceof AccountManager) {
return;
}
if (method_exists($user, 'isActive') && !$user->isActive()) {
$user->setLastAccess(new DateTime());
$this->em->persist($user);
$this->em->flush();
}
}
public static function getSubscribedEvents(): array
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::TERMINATE => [['onTerminate', 20]],
];
}
}