<?php
declare(strict_types=1);
namespace App\System\Listener\Request;
use App\Infrastructure\Interfaces\Logger\MessageDirectorInterface;
use App\Infrastructure\Interfaces\Logger\NetworkLoggerInterface;
use App\System\Infrastructure\Implementation\Logger\Request\RequestAndResponseBuilder;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestAndResponseLogListener implements EventSubscriberInterface
{
private const JSON = 'json';
public function __construct(
private readonly NetworkLoggerInterface $networkLogger,
private readonly MessageDirectorInterface $loggerDirector,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::TERMINATE => 'catchResponse',
];
}
public function catchResponse(TerminateEvent $event): void
{
$request = $event->getRequest();
$response = $event->getResponse();
$contentType = $request->getContentType();
if (!$event->isMainRequest() || $request->isXmlHttpRequest() || (!is_null($contentType) && $contentType !== self::JSON)) {
return;
}
$requestBuilder = new RequestAndResponseBuilder();
$requestBuilder
->setRequest($request)
->setResponse($response)
->setUri($request->getRequestUri())
->setMethod($request->getMethod());
$this->loggerDirector
->setMessageBuilder($requestBuilder)
->withAuthenticatedUser();
$this->networkLogger->publish($this->loggerDirector);
}
}