Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.4 kB
13
Indexable
Never
<?php

namespace App\EventListener;

use App\Entity\GrafanaRequestLog;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use JetBrains\PhpStorm\ArrayShape;
use Symfony\Bridge\Doctrine\ManagerRegistry;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Stopwatch\Stopwatch;

class RequestListener implements EventSubscriberInterface
{

    public Stopwatch $stopwatch;
    public EntityManagerInterface $em;

    public function __construct(Stopwatch $stopwatch, EntityManagerInterface $em)
    {
        $this->stopwatch = $stopwatch;
        $this->em = $em;
    }

    #[ArrayShape(['kernel.request' => "string", 'kernel.finish_request' => "string"])]
    public static function getRequestEvents()
    {
        return [
            'kernel.request' => 'onKernelRequest',
            'kernel.finish_request' => 'onKernelFinishRequest',
        ];
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $event->getRequest()->getRequestUri();
        $this->stopwatch = new Stopwatch();
        $this->stopwatch->openSection();
        $this->stopwatch->start('request_duration');
    }

    /**
     * @return Stopwatch
     */
    public function getStopwatch(): Stopwatch
    {
        $this->stopwatch->start('request_duration');
        return $this->stopwatch;
    }

    public function onKernelFinishRequest(FinishRequestEvent $finishRequestEvent)
    {

        $start = $this->getStopwatch();
        $stop = $this->stopwatch->stop('request_duration');
        $requestUri = $finishRequestEvent->getRequest()->getRequestUri();

        if(str_starts_with($requestUri, '/api')){
            $grafanaLog = new GrafanaRequestLog();
            $time = $stop->getDuration();
            $grafanaLog->setRequestTime($time);
            $grafanaLog->setEndpoint($requestUri);
            $grafanaLog->setCreatedAt(new \DateTimeImmutable());
            $this->em->persist($grafanaLog);
            $this->em->flush();
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            RequestEvent::class => 'onKernelRequest',
            FinishRequestEvent::class => 'onKernelFinishRequest',
        ];
    }
}