<?php
namespace App\EventListener;
use App\Service\Api\Avanti\AvantiException;
use App\Service\Log\LogService;
use Neomerx\JsonApi\Encoder\Encoder;
use Neomerx\JsonApi\Schema\Error;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
class ExceptionListener implements EventSubscriberInterface
{
private LogService $logService;
public function __construct(LogService $logService, KernelInterface $kernel)
{
$this->logService = $logService;
$this->env = $kernel->getEnvironment();
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$status = Response::HTTP_BAD_REQUEST;
if ($exception->getCode() and array_key_exists($exception->getCode(), Response::$statusTexts)) {
$status = $exception->getCode();
}
if (array_key_exists($status, Response::$statusTexts)) {
$codeDesc = Response::$statusTexts[$status];
} else {
$codeDesc = preg_replace('#.*?\\\#is', '', get_class($exception)); // just the class name, without the namespace
}
$trace = $exception->getTrace();
if ($exception instanceof AvantiException) {
array_unshift($trace, $exception->getAvantiError());
}
$this->logService->run([
'codeMessage' => $codeDesc,
'status' => $status,
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTraceAsString(),
'avantiError' => $exception instanceof AvantiException ? $exception->getAvantiError() : null
]);
$error = new Error(
null,
null,
null,
$status,
null,
$exception->getMessage(),
null,
$this->env === 'dev' ? $trace : null,
false
);
$event->setResponse(new JsonResponse(json_decode(Encoder::instance()->encodeError($error)), $status));
}
/**
* @return mixed[]
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
}