<?php
namespace App\EventSubscriber;
use App\Entity\Main\Traffic;
use App\Repository\Main\TrafficRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class TrafficSubscriber implements EventSubscriberInterface
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function onKernelRequest(RequestEvent $event)
{
$path = $event->getRequest()->getPathInfo();
if (!strpos($path, 'api') && !strpos($path, 'admin')) {
$createdAt = new \DateTime();
$createdAt->setTime($createdAt->format('H'), 0);
/** @var TrafficRepository $trafficRepository */
$trafficRepository = $this->entityManager->getRepository(Traffic::class);
/** @var Traffic $t */
$t = $trafficRepository->findOneBy([
'createdAt' => $createdAt,
]);
if ($t) {
$t->setCount($t->getCount() + 1);
} else {
$t = new Traffic();
$t->setCreatedAt($createdAt);
}
$this->entityManager->persist($t);
$this->entityManager->flush();
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [
[ 'onKernelRequest', 20 ],
],
];
}
}