<?php
namespace AppBundle\EventListener;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Doctrine\ORM\EntityManager;
use AppBundle\Entity\UserActivity;
use BMD\BeLABundle\Entity\UserEntity;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
/**
* Listener that updates the last activity of the authenticated user
*/
class ActivityListener
{
protected $authChecker;
protected $entityManager;
protected $securityTokenStorage;
public function __construct(AuthorizationCheckerInterface $authChecker, TokenStorageInterface $securityTokenStorage, EntityManager $entityManager)
{
$this->authChecker = $authChecker;
$this->entityManager = $entityManager;
$this->securityTokenStorage = $securityTokenStorage;
}
/**
* Update the user "lastActivity" on each request
* @param FilterControllerEvent $event
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onCoreController(FilterControllerEvent $event)
{
// Check that the current request is a "MASTER_REQUEST"
// Ignore any sub-request
if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
return;
}
try {
// Check token authentication availability
if ($this->authChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
$user = $this->securityTokenStorage->getToken()->getUser();
if ($user instanceof UserEntity) {
$userId = $user->getUserId();
$activity = $this->entityManager->getRepository(UserActivity::class)->findOneByUserId($userId);
if (null == $activity) {
$activity = new UserActivity();
$activity->setUserId($userId);
}
$activity->setFullName($user->getFirstName().' '.$user->getLastName());
$activity->setLastActivity(new \DateTime());
$this->entityManager->persist($activity);
$this->entityManager->flush();
}
}
} catch (AuthenticationCredentialsNotFoundException $e) {
}
}
}