<?php
namespace App\EventListener;
use Datetime;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\HttpKernel;
/**
* Listener that updates the last activity of the authenticated user
*/
class ActivityListener
{
protected $security;
protected $entityManager;
public function __construct(Security $security, EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->entityManager = $entityManager;
}
/**
* Update the user "lastActivity" on each request
* @param FilterControllerEvent $event
*/
public function onCoreController(ControllerEvent $event)
{
// Check that the current request is a "MASTER_REQUEST"
// Ignore any sub-request
if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
return;
}
// Check token authentication availability
if ($this->security->getToken()) {
$user = $this->security->getToken()->getUser();
if ($user instanceof UserInterface) {
$user->setLastActive(new Datetime);
$this->entityManager->flush();
}
}
}
}