src/System/Listener/Request/RequestAndResponseLogListener.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\System\Listener\Request;
  4. use App\Infrastructure\Interfaces\Logger\MessageDirectorInterface;
  5. use App\Infrastructure\Interfaces\Logger\NetworkLoggerInterface;
  6. use App\System\Infrastructure\Implementation\Logger\Request\RequestAndResponseBuilder;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class RequestAndResponseLogListener implements EventSubscriberInterface
  11. {
  12.     private const JSON 'json';
  13.     public function __construct(
  14.         private readonly NetworkLoggerInterface $networkLogger,
  15.         private readonly MessageDirectorInterface $loggerDirector,
  16.     ) {
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::TERMINATE => 'catchResponse',
  22.         ];
  23.     }
  24.     public function catchResponse(TerminateEvent $event): void
  25.     {
  26.         $request $event->getRequest();
  27.         $response $event->getResponse();
  28.         $contentType $request->getContentType();
  29.         if (!$event->isMainRequest() || $request->isXmlHttpRequest() || (!is_null($contentType) && $contentType !== self::JSON)) {
  30.             return;
  31.         }
  32.         $requestBuilder = new RequestAndResponseBuilder();
  33.         $requestBuilder
  34.             ->setRequest($request)
  35.             ->setResponse($response)
  36.             ->setUri($request->getRequestUri())
  37.             ->setMethod($request->getMethod());
  38.         $this->loggerDirector
  39.             ->setMessageBuilder($requestBuilder)
  40.             ->withAuthenticatedUser();
  41.         $this->networkLogger->publish($this->loggerDirector);
  42.     }
  43. }