<?php
namespace App\EventListener;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Listener that updates the last activity of the authenticated user
*/
class ActivityListener
{
protected $container;
protected $em;
public function __construct(ContainerInterface $container, EntityManagerInterface $em)
{
$this->container = $container;
$this->em = $em;
}
/**
* Update the user "lastActivity" on each request
* @param ControllerEvent $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->container->get('security.token_storage')->getToken()) {
//$user = $this->securityContext->getToken()->getUser();
$user = $this->container->get('security.token_storage')->getToken()->getUser();
if ( ($user instanceof User) && !($user->isActiveNow()) ) {
//dd($user);
$user->setLastActivity(new \DateTime());
$this->em->persist($user);
$this->em->flush();
}
}
}
}