<?php
namespace App\Listener;
use App\Message\LogMessage;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Messenger\MessageBusInterface;
class ResponseListener
{
public function __construct(
private MessageBusInterface $bus
) {
}
public function onKernelResponse(ResponseEvent $event): ResponseEvent
{
if (!isset($_ENV['LOGGER_KEY']) || !$_ENV['LOGGER_KEY']) {
return $event;
}
$response = $event->getResponse();
if ($response->headers->get('Content-Type') === 'application/json') {
$request = $event->getRequest();
$user = null;
if ($customer = $request->attributes->get('customer')) {
$user = sprintf('%s - %s - %s', $customer->getHash(), $customer->getFullname(), $customer->getEmail());
}
if ($employee = $request->attributes->get('employee')) {
$user = sprintf('%s - %s - %s', $employee->getHash(), $employee->getFullname(), $employee->getEmail());
}
$data = [
'requestHeaders' => $request->headers->all(),
'requestContent' => $request->getContent(),
'requestUri' => $request->getUri(),
'requestMethod' => $request->getMethod(),
'requestIp' => $request->getClientIp(),
'responseCode' => $response->getStatusCode(),
'responseContent' => json_decode((string)$response->getContent(), true),
'environment' => $_ENV['APP_ENV'],
'user' => $user
];
$this->bus->dispatch(new LogMessage($data));
}
return $event;
}
public function onKernelException(ExceptionEvent $event): KernelEvent
{
$response = new JsonResponse(['error' => $event->getThrowable()->getMessage()]);
$event->setResponse($response);
return $event;
}
}