src/EventSubscriber/LastActionSubscriber.php line 38

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. /**
  12.  * Subscription to update the last user action time.
  13.  *
  14.  */
  15. class LastActionSubscriber implements EventSubscriberInterface
  16. {
  17.     private EntityManagerInterface $em;
  18.     public function __construct(private readonly ManagerRegistry $doctrine, private readonly TokenStorageInterface $tokenStorage)
  19.     {
  20.         $this->em $doctrine->getManager();
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         // return the subscribed events, their methods and priorities
  25.         return [
  26.             KernelEvents::FINISH_REQUEST => [
  27.                 ['updateLastAction', -10],
  28.             ],
  29.         ];
  30.     }
  31.     public function updateLastAction(FinishRequestEvent $event): void
  32.     {
  33.         $accessToken $this->tokenStorage->getToken();
  34.         if (null !== $accessToken) {
  35.             /* @var $user User */
  36.             $user $accessToken->getUser();
  37.             if ($user instanceof User) {
  38.                 // load user using a different entity manager
  39.                 // this prevents unintended behavior e.g. when a user is edited with violations this flush here would course that the fields are updated anyway
  40.                 $user2 $this->em->getRepository(User::class)->find($user->getId());
  41.                 if ($this->em->isOpen()) {
  42.                     $user2->setLastAction(new \DateTime());
  43.                     $this->em->persist($user2);
  44.                     $this->em->flush();
  45.                 }
  46.             }
  47.         }
  48.     }
  49. }