<?php
namespace App\EventSubscriber;
use App\Entity\UserActivity;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
class UserActivitySubscriber implements EventSubscriberInterface
{
private $entityManager;
private $security;
public function __construct(EntityManagerInterface $entityManager, Security $security)
{
$this->entityManager = $entityManager;
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$route = $request->attributes->get('_route');
$user = $this->security->getUser();
$sessionId = $request->getSession()->getId();
$timestamp = new \DateTime();
if ($user && $route) {
$userActivity = new UserActivity();
$userActivity->setUser($user);
$userActivity->setRoute($route);
$userActivity->setSessionId($sessionId);
$userActivity->setTimestamp($timestamp);
$this->entityManager->persist($userActivity);
$this->entityManager->flush();
}
}
}