src/System/Listener/Response/ResponseExceptionListener.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\System\Listener\Response;
  3. use App\System\Validation\ConstraintsViolationException;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\Validator\ConstraintViolationInterface;
  8. use Throwable;
  9. class ResponseExceptionListener
  10. {
  11.     public function onKernelException(ExceptionEvent $event): void
  12.     {
  13.         if (!$event->isMainRequest()) {
  14.             return;
  15.         }
  16.         $exception $event->getThrowable();
  17.         if ($exception instanceof ConstraintsViolationException) {
  18.             $content $this->normalizeConstraintsViolation($exception);
  19.             $code Response::HTTP_UNPROCESSABLE_ENTITY;
  20.         } else {
  21.             $content $this->normalizeUseCaseException($exception);
  22.             $code Response::HTTP_BAD_REQUEST;
  23.         }
  24.         $response = new JsonResponse();
  25.         $response
  26.             ->setStatusCode($code)
  27.             ->setContent(json_encode($content));
  28.         $event->setResponse($response);
  29.     }
  30.     private function normalizeConstraintsViolation(ConstraintsViolationException $exception): array
  31.     {
  32.         $violations = [];
  33.         foreach ($exception->getConstraints() as $constraint) {
  34.             /* @var ConstraintViolationInterface $constraint */
  35.             $violations[] = [
  36.                 'propertyPath' => $constraint->getPropertyPath(),
  37.                 'title' => $constraint->getMessage(),
  38.                 'parameters' => [],
  39.             ];
  40.         }
  41.         return [
  42.             'title' => 'constraints violation',
  43.             'status' => 422,
  44.             'detail' => $exception->getMessage(),
  45.             'codes' => [],
  46.             'violations' => $violations,
  47.         ];
  48.     }
  49.     private function normalizeUseCaseException(Throwable $exception): array
  50.     {
  51.         return [
  52.             'title' => 'Bad Request',
  53.             'status' => 400,
  54.             'detail' => $exception->getMessage(),
  55.             'codes' => $exception->getCode(),
  56.             'violations' => [],
  57.         ];
  58.     }
  59. }