src/Listener/ResponseListener.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Listener;
  3. use App\Message\LogMessage;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Event\KernelEvent;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. use Symfony\Component\Messenger\MessageBusInterface;
  9. class ResponseListener
  10. {
  11.     public function __construct(
  12.         private MessageBusInterface $bus
  13.     ) {
  14.     }
  15.     public function onKernelResponse(ResponseEvent $event): ResponseEvent
  16.     {
  17.         if (!isset($_ENV['LOGGER_KEY']) || !$_ENV['LOGGER_KEY']) {
  18.             return $event;
  19.         }
  20.         $response $event->getResponse();
  21.         if ($response->headers->get('Content-Type') === 'application/json') {
  22.             $request $event->getRequest();
  23.             $user null;
  24.             if ($customer $request->attributes->get('customer')) {
  25.                 $user sprintf('%s - %s - %s'$customer->getHash(), $customer->getFullname(), $customer->getEmail());
  26.             }
  27.             if ($employee $request->attributes->get('employee')) {
  28.                 $user sprintf('%s - %s - %s'$employee->getHash(), $employee->getFullname(), $employee->getEmail());
  29.             }
  30.             $data = [
  31.                 'requestHeaders' => $request->headers->all(),
  32.                 'requestContent' => $request->getContent(),
  33.                 'requestUri' => $request->getUri(),
  34.                 'requestMethod' => $request->getMethod(),
  35.                 'requestIp' => $request->getClientIp(),
  36.                 'responseCode' => $response->getStatusCode(),
  37.                 'responseContent' => json_decode((string)$response->getContent(), true),
  38.                 'environment' => $_ENV['APP_ENV'],
  39.                 'user' => $user
  40.             ];
  41.             $this->bus->dispatch(new LogMessage($data));
  42.         }
  43.         return $event;
  44.     }
  45.     public function onKernelException(ExceptionEvent $event): KernelEvent
  46.     {
  47.         $response = new JsonResponse(['error' => $event->getThrowable()->getMessage()]);
  48.         $event->setResponse($response);
  49.         return $event;
  50.     }
  51. }