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

  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 Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  17. use Symfony\Component\Serializer\SerializerInterface;
  18. /**
  19.  * Handles validation errors.
  20.  *
  21.  * @author Kévin Dunglas <dunglas@gmail.com>
  22.  */
  23. final class ValidationExceptionListener
  24. {
  25.     public function __construct(private readonly SerializerInterface $serializer, private readonly array $errorFormats, private readonly array $exceptionToStatus = [])
  26.     {
  27.     }
  28.     /**
  29.      * Returns a list of violations normalized in the Hydra format.
  30.      */
  31.     public function onKernelException(ExceptionEvent $event): void
  32.     {
  33.         $exception $event->getThrowable();
  34.         if (!$exception instanceof ConstraintViolationListAwareExceptionInterface && !$exception instanceof FilterValidationException) {
  35.             return;
  36.         }
  37.         $exceptionClass $exception::class;
  38.         $statusCode Response::HTTP_UNPROCESSABLE_ENTITY;
  39.         foreach ($this->exceptionToStatus as $class => $status) {
  40.             if (is_a($exceptionClass$classtrue)) {
  41.                 $statusCode $status;
  42.                 break;
  43.             }
  44.         }
  45.         $format ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);
  46.         $event->setResponse(new Response(
  47.             $this->serializer->serialize($exception instanceof ConstraintViolationListAwareExceptionInterface $exception->getConstraintViolationList() : $exception$format['key']),
  48.             $statusCode,
  49.             [
  50.                 'Content-Type' => sprintf('%s; charset=utf-8'$format['value'][0]),
  51.                 'X-Content-Type-Options' => 'nosniff',
  52.                 'X-Frame-Options' => 'deny',
  53.             ]
  54.         ));
  55.     }
  56. }