src/Platform/EventListener/APIValidationExceptionEventListener.php line 15

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Platform\EventListener;
  4. use App\Platform\Exception\APIValidationException;
  5. use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. #[AsEventListener(eventExceptionEvent::class, method'onKernelException')]
  9. class APIValidationExceptionEventListener
  10. {
  11.     public function onKernelException(ExceptionEvent $event): void
  12.     {
  13.         $exception $event->getThrowable();
  14.         if ($exception instanceof APIValidationException) {
  15.             /** @var int $code */
  16.             $code $exception->getStatusCode();
  17.             $response = new JsonResponse(status$code);
  18.             $responseData = [];
  19.             foreach ($exception->getList() as $item) {
  20.                 $responseData[] = [
  21.                     'error' => $item->getMessage(),
  22.                     'atPath' => $item->getPropertyPath(),
  23.                 ];
  24.             }
  25.             $response->setData($responseData);
  26.             $event->setResponse($response);
  27.         }
  28.     }
  29. }