src/EventListener/ApiExceptionListener.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Exception\APIBadRequestHttpException;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\Validator\ConstraintViolationInterface;
  7. class ApiExceptionListener
  8. {
  9.     public function onKernelException(ExceptionEvent $exceptionEvent)
  10.     {
  11.         $event $exceptionEvent->getException();
  12.         if (!$event instanceof APIBadRequestHttpException) {
  13.             return;
  14.         }
  15.         $violationsArray = [];
  16.         if ($event->getViolations()) {
  17.             foreach ($event->getViolations() as $violation) {
  18.                 /** @var ConstraintViolationInterface $violation */
  19.                 $violationsArray[] = [
  20.                     $violation->getPropertyPath() => $violation->getMessage()
  21.                 ];
  22.             }
  23.         }
  24.         $responseArray = [
  25.             'message' => $event->getMessage(),
  26.             'violations' => $violationsArray,
  27.             'code' => $event->getCode()
  28.         ];
  29.         $response = new JsonResponse(
  30.             $responseArray,
  31.             $event->getCode()
  32.         );
  33.         $exceptionEvent->setResponse($response);
  34.     }
  35. }