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

Open in your IDE?
  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\Core\Bridge\Symfony\Validator\EventListener;
  12. use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
  13. use ApiPlatform\Core\Util\ErrorFormatGuesser;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  16. use Symfony\Component\Serializer\SerializerInterface;
  17. /**
  18.  * Handles validation errors.
  19.  *
  20.  * @author Kévin Dunglas <dunglas@gmail.com>
  21.  */
  22. final class ValidationExceptionListener
  23. {
  24.     private $serializer;
  25.     private $errorFormats;
  26.     public function __construct(SerializerInterface $serializer, array $errorFormats)
  27.     {
  28.         $this->serializer $serializer;
  29.         $this->errorFormats $errorFormats;
  30.     }
  31.     /**
  32.      * Returns a list of violations normalized in the Hydra format.
  33.      */
  34.     public function onKernelException(ExceptionEvent $event): void
  35.     {
  36.         $exception method_exists($event'getThrowable') ? $event->getThrowable() : $event->getException();
  37.         if (!$exception instanceof ValidationException) {
  38.             return;
  39.         }
  40.         $format ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);
  41.         $event->setResponse(new Response(
  42.                 $this->serializer->serialize($exception->getConstraintViolationList(), $format['key']),
  43.                 Response::HTTP_BAD_REQUEST,
  44.                 [
  45.                     'Content-Type' => sprintf('%s; charset=utf-8'$format['value'][0]),
  46.                     'X-Content-Type-Options' => 'nosniff',
  47.                     'X-Frame-Options' => 'deny',
  48.                 ]
  49.         ));
  50.     }
  51. }