<?php
namespace App\EventSubscriber;
use App\Entity\RouteConfig;
use App\Entity\User;
use App\Entity\UserActivity;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\Security;
class RequestSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var Security
*/
private $security;
public function __construct(EntityManagerInterface $em, Security $security)
{
$this->em = $em;
$this->security = $security;
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
// ResponseEvent::class => 'onKernelResponse',
];
}
public function onKernelRequest(RequestEvent $event): bool
{
$req = $event->getRequest();
$controller = $req->attributes->get('_controller');
$ctrArr = explode('::', $controller);
$controllerPath = $ctrArr[0] ?? '';
$actionName = $ctrArr[1] ?? '';
if (!$controllerPath || !$actionName) {
return false;
}
// check first time login
if ($this->security->getUser()) {
/** @var User $user */
$user = $this->security->getUser();
if ('user_change_password' != $req->attributes->get('_route')) {
if ($user->isIsNew()) {
$event->setResponse(new RedirectResponse('/users/change-password'));
return false;
}
}
}
if (strpos(strtolower($actionName), 'json')) {
return false;
}
/** @var User $user */
$user = $this->security->getUser();
if ($user) {
$rRepo = $this->em->getRepository(RouteConfig::class);
/** @var RouteConfig $route */
$route = $rRepo->findOneBy([
'name' => $req->attributes->get('_route'),
'isTrack' => true,
]);
if ($route) {
$activity = new UserActivity();
$activity->setType('ACCESS');
$activity->setUser($user);
$activity->setName($route->getLabel() ?: $route->getName());
$activity->setActiveAt(new \DateTime('now'));
$activity->setRouteName($req->attributes->get('_route'));
$activity->setRouteParams($req->attributes->get('_route_params'));
$activity->setPathInfo($req->getPathInfo());
$activity->setRequestUri($req->getRequestUri());
$activity->setRequestMethod($req->getRealMethod());
$activity->setCtrName($controllerPath);
$activity->setActName($actionName);
$options = [
'platform' => $req->headers->get('sec-ch-ua-platform'),
'user-agent' => $req->headers->get('user-agent'),
'referer' => $req->headers->get('referer'),
];
$activity->setOptions($options);
$this->em->persist($activity);
$this->em->flush();
}
}
return true;
}
public function onKernelResponse(ResponseEvent $event)
{
}
}