<?php
namespace App\Domain\Shared\Http\Listener;
use App\Domain\Shared\Http\ApiResponse;
use App\Domain\Shared\Http\Factory\NormalizerFactory;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
/**
* @var NormalizerFactory
*/
private $normalizerFactory;
/**
* ExceptionListener constructor.
*/
public function __construct(NormalizerFactory $normalizerFactory)
{
$this->normalizerFactory = $normalizerFactory;
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$request = $event->getRequest();
if (in_array('application/json', $request->getAcceptableContentTypes())) {
$response = $this->createApiResponse($exception);
$event->setResponse($response);
}
}
/**
* Creates the ApiResponse from any Exception.
*
* @return ApiResponse
*/
private function createApiResponse($exception)
{
$normalizer = $this->normalizerFactory->getNormalizer($exception);
$statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR;
try {
$errors = $normalizer ? $normalizer->normalize($exception) : [];
} catch (\Exception $e) {
$errors = [];
}
return new ApiResponse(true, $exception->getMessage(),null, $errors, $statusCode);
}
}