src/EventListener/Exception/ExceptionListener.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventListener\Exception;
  3. use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
  4. use ApiPlatform\Core\Util\ErrorFormatGuesser;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\Serializer\SerializerInterface;
  8. class ExceptionListener
  9. {
  10.     private SerializerInterface $serializer;
  11.     private array $errorFormats;
  12.     public function __construct(SerializerInterface $serializer, array $errorFormats)
  13.     {
  14.         $this->serializer $serializer;
  15.         $this->errorFormats $errorFormats;
  16.     }
  17.     public function onKernelException(ExceptionEvent $event)
  18.     {
  19.         $exception method_exists($event'getThrowable') ? $event->getThrowable() : $event->getException();
  20.         if (!$exception instanceof ValidationException) {
  21.             return;
  22.         }
  23.         $codesList = [];
  24.         $constraintList $exception->getConstraintViolationList();
  25.         foreach ($constraintList as $k => $c) {
  26.             $codesList[$k] =
  27.                 $c->getCode() ??
  28.                 hash("md5"get_class($c->getConstraint()));
  29.         }
  30.         $format ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);
  31.         $serializedError $this->serializer->serialize($constraintList$format['key']);
  32.         $response json_decode($serializedErrortrue);
  33.         foreach ($response["violations"] as $k => $v) {
  34.             $response["violations"][$k]["code"] = $codesList[$k];
  35.         }
  36.         $serializedError json_encode($response);
  37.         $event->setResponse(new Response(
  38.             $serializedError,
  39.             Response::HTTP_BAD_REQUEST,
  40.             [
  41.                 'Content-Type' => sprintf('%s; charset=utf-8'$format['value'][0]),
  42.                 'X-Content-Type-Options' => 'nosniff',
  43.                 'X-Frame-Options' => 'deny',
  44.             ]
  45.         ));
  46.     }
  47. }