vendor/api-platform/core/src/Symfony/Validator/EventListener/ValidationExceptionListener.php line 38

  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Symfony\Validator\EventListener;
  12. use ApiPlatform\Exception\FilterValidationException;
  13. use ApiPlatform\Symfony\Validator\Exception\ConstraintViolationListAwareExceptionInterface;
  14. use ApiPlatform\Util\ErrorFormatGuesser;
  15. use ApiPlatform\Validator\Exception\ValidationException;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  18. use Symfony\Component\Serializer\SerializerInterface;
  19. /**
  20.  * Handles validation errors.
  21.  *
  22.  * @author Kévin Dunglas <dunglas@gmail.com>
  23.  */
  24. final class ValidationExceptionListener
  25. {
  26.     public function __construct(private readonly SerializerInterface $serializer, private readonly array $errorFormats, private readonly array $exceptionToStatus = [])
  27.     {
  28.     }
  29.     /**
  30.      * Returns a list of violations normalized in the Hydra format.
  31.      */
  32.     public function onKernelException(ExceptionEvent $event): void
  33.     {
  34.         $exception $event->getThrowable();
  35.         if (!$exception instanceof ConstraintViolationListAwareExceptionInterface && !$exception instanceof FilterValidationException) {
  36.             return;
  37.         }
  38.         $exceptionClass $exception::class;
  39.         $statusCode Response::HTTP_UNPROCESSABLE_ENTITY;
  40.         foreach ($this->exceptionToStatus as $class => $status) {
  41.             if (is_a($exceptionClass$classtrue)) {
  42.                 $statusCode $status;
  43.                 break;
  44.             }
  45.         }
  46.         $format ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);
  47.         $context = [];
  48.         if ($exception instanceof ValidationException && ($errorTitle $exception->getErrorTitle())) {
  49.             $context['title'] = $errorTitle;
  50.         }
  51.         $event->setResponse(new Response(
  52.             $this->serializer->serialize($exception instanceof ConstraintViolationListAwareExceptionInterface $exception->getConstraintViolationList() : $exception$format['key'], $context),
  53.             $statusCode,
  54.             [
  55.                 'Content-Type' => sprintf('%s; charset=utf-8'$format['value'][0]),
  56.                 'X-Content-Type-Options' => 'nosniff',
  57.                 'X-Frame-Options' => 'deny',
  58.             ]
  59.         ));
  60.     }
  61. }