ApiPlatform\Core\Bridge\Symfony\Validator\EventListener\ValidationExceptionListener::onKernelException PHP Method

onKernelException() public method

Returns a list of violations normalized in the Hydra format.
public onKernelException ( GetResponseForExceptionEvent $event )
$event Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        if (!$exception instanceof ValidationException) {
            return;
        }
        $format = ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);
        $event->setResponse(new Response($this->serializer->serialize($exception->getConstraintViolationList(), $format['key']), Response::HTTP_BAD_REQUEST, ['Content-Type' => sprintf('%s; charset=utf-8', $format['value'][0]), 'X-Content-Type-Options' => 'nosniff', 'X-Frame-Options' => 'deny']));
    }

Usage Example

 public function testValidationException()
 {
     $list = new ConstraintViolationList([]);
     $eventProphecy = $this->prophesize(GetResponseForExceptionEvent::class);
     $eventProphecy->getException()->willReturn(new ValidationException($list))->shouldBeCalled();
     $eventProphecy->getRequest()->willReturn(new Request())->shouldBeCalled();
     $eventProphecy->setResponse(new Response('{"foo": "bar"}', Response::HTTP_BAD_REQUEST, ['Content-Type' => 'application/ld+json; charset=utf-8', 'X-Content-Type-Options' => 'nosniff', 'X-Frame-Options' => 'deny']))->shouldBeCalled();
     $serializerProphecy = $this->prophesize(SerializerInterface::class);
     $serializerProphecy->serialize($list, 'hydra')->willReturn('{"foo": "bar"}')->shouldBeCalled();
     $listener = new ValidationExceptionListener($serializerProphecy->reveal(), ['hydra' => ['application/ld+json']]);
     $listener->onKernelException($eventProphecy->reveal());
 }
ValidationExceptionListener