ApiPlatform\Core\Hydra\Serializer\ConstraintViolationListNormalizer::normalize PHP Method

normalize() public method

public normalize ( $object, $format = null, array $context = [] )
$context array
    public function normalize($object, $format = null, array $context = [])
    {
        $violations = [];
        $messages = [];
        foreach ($object as $violation) {
            $violations[] = ['propertyPath' => $violation->getPropertyPath(), 'message' => $violation->getMessage()];
            $propertyPath = $violation->getPropertyPath();
            $prefix = $propertyPath ? sprintf('%s: ', $propertyPath) : '';
            $messages[] = $prefix . $violation->getMessage();
        }
        return ['@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'ConstraintViolationList']), '@type' => 'ConstraintViolationList', 'hydra:title' => $context['title'] ?? 'An error occurred', 'hydra:description' => $messages ? implode("\n", $messages) : (string) $object, 'violations' => $violations];
    }

Usage Example

    public function testNormalize()
    {
        $urlGeneratorProphecy = $this->prophesize(UrlGeneratorInterface::class);
        $urlGeneratorProphecy->generate('api_jsonld_context', ['shortName' => 'ConstraintViolationList'])->willReturn('/context/foo')->shouldBeCalled();
        $normalizer = new ConstraintViolationListNormalizer($urlGeneratorProphecy->reveal());
        $list = new ConstraintViolationList([new ConstraintViolation('a', 'b', [], 'c', 'd', 'e'), new ConstraintViolation('1', '2', [], '3', '4', '5')]);
        $expected = ['@context' => '/context/foo', '@type' => 'ConstraintViolationList', 'hydra:title' => 'An error occurred', 'hydra:description' => 'd: a
4: 1', 'violations' => [['propertyPath' => 'd', 'message' => 'a'], ['propertyPath' => '4', 'message' => '1']]];
        $this->assertEquals($expected, $normalizer->normalize($list));
    }
ConstraintViolationListNormalizer