src/EventListener/ActivityListener.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
  4. use Symfony\Component\Security\Core\SecurityContextInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  7. use Symfony\Component\HttpKernel\HttpKernel;
  8. use Doctrine\ORM\EntityManager;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use App\Entity\User;
  11. use Doctrine\Bundle\DoctrineBundle\Registry;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13. /**
  14.  * Listener that updates the last activity of the authenticated user
  15.  */
  16. class ActivityListener
  17. {
  18.     protected $container;
  19.     protected $em;
  20.     public function __construct(ContainerInterface $containerEntityManagerInterface $em)
  21.     {
  22.         $this->container $container;
  23.         $this->em $em;
  24.     }
  25.     /**
  26.     * Update the user "lastActivity" on each request
  27.     * @param ControllerEvent $event
  28.     */
  29.     public function onCoreController(ControllerEvent $event)
  30.     {
  31.         // Check that the current request is a "MASTER_REQUEST"
  32.         // Ignore any sub-request
  33.         if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
  34.             return;
  35.         }
  36.         // Check token authentication availability
  37.         if ($this->container->get('security.token_storage')->getToken()) {
  38.             //$user = $this->securityContext->getToken()->getUser();
  39.             
  40.             $user $this->container->get('security.token_storage')->getToken()->getUser();
  41.             if ( ($user instanceof User) && !($user->isActiveNow()) ) {
  42.                 //dd($user);
  43.                 $user->setLastActivity(new \DateTime());
  44.                 $this->em->persist($user);
  45.                 $this->em->flush();
  46.             }
  47.         }
  48.     }
  49. }