Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4b657c2

Browse files
committed
[Serializer] Fix and improve constraintViolationListNormalizer's RFC7807 compliance
1 parent 68eda49 commit 4b657c2

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,19 +34,29 @@ public function normalize($object, $format = null, array $context = array())
3434
foreach ($object as $violation) {
3535
$violations[] = array(
3636
'propertyPath' => $violation->getPropertyPath(),
37-
'message' => $violation->getMessage(),
38-
'code' => $violation->getCode(),
37+
'type' => sprintf('urn:uuid:%s', $violation->getCode()),
38+
'title' => $violation->getMessage(),
3939
);
4040
$propertyPath = $violation->getPropertyPath();
4141
$prefix = $propertyPath ? sprintf('%s: ', $propertyPath) : '';
4242
$messages[] = $prefix.$violation->getMessage();
4343
}
4444

45-
return array(
46-
'title' => isset($context['title']) ? $context['title'] : 'An error occurred',
47-
'detail' => $messages ? implode("\n", $messages) : '',
48-
'violations' => $violations,
45+
$result = array(
46+
'type' => $context['type'] ?? 'https://symfony.com/doc/current/validation.html',
47+
'title' => $context['title'] ?? 'Validation Failed',
4948
);
49+
if (isset($context['status'])) {
50+
$result['status'] = $context['status'];
51+
}
52+
if ($messages) {
53+
$result['detail'] = implode("\n", $messages);
54+
}
55+
if (isset($context['instance'])) {
56+
$result['instance'] = $context['instance'];
57+
}
58+
59+
return $result + ['violations' => $violations];
5060
}
5161

5262
/**

src/Symfony/Component/Serializer/Tests/Normalizer/ConstraintViolationListNormalizerTest.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,20 @@ public function testNormalize()
4343
));
4444

4545
$expected = array(
46-
'title' => 'An error occurred',
46+
'type' => 'https://symfony.com/doc/current/validation.html',
47+
'title' => 'Validation Failed',
4748
'detail' => 'd: a
4849
4: 1',
4950
'violations' => array(
5051
array(
5152
'propertyPath' => 'd',
52-
'message' => 'a',
53-
'code' => 'f',
53+
'type' => 'urn:uuid:f',
54+
'title' => 'a',
5455
),
5556
array(
5657
'propertyPath' => '4',
57-
'message' => '1',
58-
'code' => '6',
58+
'type' => 'urn:uuid:6',
59+
'title' => '1',
5960
),
6061
),
6162
);

0 commit comments

Comments
 (0)