src/EventListener/ActivityListener.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Datetime;
  4. use Symfony\Component\Security\Core\User\UserInterface;
  5. use Symfony\Component\Security\Core\Security;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\HttpKernel\HttpKernel;
  9. /**
  10.  * Listener that updates the last activity of the authenticated user
  11.  */
  12. class ActivityListener
  13. {
  14.     protected $security;
  15.     protected $entityManager;
  16.     public function __construct(Security $securityEntityManagerInterface $entityManager)
  17.     {
  18.         $this->security $security;
  19.         $this->entityManager $entityManager;
  20.     }
  21.     /**
  22.     * Update the user "lastActivity" on each request
  23.     * @param FilterControllerEvent $event
  24.     */
  25.     public function onCoreController(ControllerEvent $event)
  26.     {
  27.         // Check that the current request is a "MASTER_REQUEST"
  28.         // Ignore any sub-request
  29.         if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
  30.             return;
  31.         }
  32.         // Check token authentication availability
  33.         if ($this->security->getToken()) {
  34.             $user $this->security->getToken()->getUser();
  35.             if ($user instanceof UserInterface) {
  36.                 $user->setLastActive(new Datetime);
  37.                 $this->entityManager->flush();
  38.             }
  39.         }
  40.     }
  41. }