src/EventSubscriber/UserActivitySubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\UserActivity;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Security;
  9. class UserActivitySubscriber implements EventSubscriberInterface
  10. {
  11.     private $entityManager;
  12.     private $security;
  13.     public function __construct(EntityManagerInterface $entityManagerSecurity $security)
  14.     {
  15.         $this->entityManager $entityManager;
  16.         $this->security $security;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             KernelEvents::REQUEST => 'onKernelRequest',
  22.         ];
  23.     }
  24.     public function onKernelRequest(RequestEvent $event)
  25.     {
  26.         $request $event->getRequest();
  27.         $route $request->attributes->get('_route');
  28.         $user $this->security->getUser();
  29.         $sessionId $request->getSession()->getId();
  30.         $timestamp = new \DateTime();
  31.         if ($user && $route) {
  32.             $userActivity = new UserActivity();
  33.             $userActivity->setUser($user);
  34.             $userActivity->setRoute($route);
  35.             $userActivity->setSessionId($sessionId);
  36.             $userActivity->setTimestamp($timestamp);
  37.             $this->entityManager->persist($userActivity);
  38.             $this->entityManager->flush();
  39.         }
  40.     }
  41. }