src/AppBundle/EventListener/ActivityListener.php line 35

Open in your IDE?
  1. <?php
  2. namespace AppBundle\EventListener;
  3. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  4. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  5. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  6. use Symfony\Component\HttpKernel\HttpKernel;
  7. use Doctrine\ORM\EntityManager;
  8. use AppBundle\Entity\UserActivity;
  9. use BMD\BeLABundle\Entity\UserEntity;
  10. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  11. /**
  12.  * Listener that updates the last activity of the authenticated user
  13.  */
  14. class ActivityListener
  15. {
  16.     protected $authChecker;
  17.     protected $entityManager;
  18.     protected $securityTokenStorage;
  19.     public function __construct(AuthorizationCheckerInterface $authCheckerTokenStorageInterface $securityTokenStorageEntityManager $entityManager)
  20.     {
  21.         $this->authChecker $authChecker;
  22.         $this->entityManager $entityManager;
  23.         $this->securityTokenStorage $securityTokenStorage;
  24.     }
  25.     /**
  26.      * Update the user "lastActivity" on each request
  27.      * @param FilterControllerEvent $event
  28.      * @throws \Doctrine\ORM\ORMException
  29.      * @throws \Doctrine\ORM\OptimisticLockException
  30.      */
  31.     public function onCoreController(FilterControllerEvent $event)
  32.     {
  33.         // Check that the current request is a "MASTER_REQUEST"
  34.         // Ignore any sub-request
  35.         if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
  36.             return;
  37.         }
  38.         
  39.         try {
  40.           // Check token authentication availability
  41.             if ($this->authChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
  42.                 $user $this->securityTokenStorage->getToken()->getUser();
  43.                 if ($user instanceof UserEntity) {
  44.                     $userId $user->getUserId();
  45.                     $activity $this->entityManager->getRepository(UserActivity::class)->findOneByUserId($userId);
  46.                     if (null == $activity) {
  47.                         $activity = new UserActivity();
  48.                         $activity->setUserId($userId);
  49.                     }
  50.                     $activity->setFullName($user->getFirstName().' '.$user->getLastName());
  51.                     $activity->setLastActivity(new \DateTime());
  52.                     $this->entityManager->persist($activity);
  53.                     $this->entityManager->flush();
  54.                 }
  55.             }
  56.         } catch (AuthenticationCredentialsNotFoundException $e) {
  57.         }
  58.     }
  59. }