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

Skip to content

Commit 3c789c6

Browse files
dunglasfabpot
authored andcommitted
[Serializer] Fix and improve constraintViolationListNormalizer's RFC7807 compliance
1 parent 68eda49 commit 3c789c6

File tree

2 files changed

+31
-14
lines changed

2 files changed

+31
-14
lines changed

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

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,21 +32,37 @@ public function normalize($object, $format = null, array $context = array())
3232
$violations = array();
3333
$messages = array();
3434
foreach ($object as $violation) {
35-
$violations[] = array(
36-
'propertyPath' => $violation->getPropertyPath(),
37-
'message' => $violation->getMessage(),
38-
'code' => $violation->getCode(),
39-
);
4035
$propertyPath = $violation->getPropertyPath();
36+
37+
$violationEntry = array(
38+
'propertyPath' => $propertyPath,
39+
'title' => $violation->getMessage(),
40+
);
41+
if (null !== $code = $violation->getCode()) {
42+
$violationEntry['type'] = sprintf('urn:uuid:%s', $code);
43+
}
44+
45+
$violations[] = $violationEntry;
46+
4147
$prefix = $propertyPath ? sprintf('%s: ', $propertyPath) : '';
4248
$messages[] = $prefix.$violation->getMessage();
4349
}
4450

45-
return array(
46-
'title' => isset($context['title']) ? $context['title'] : 'An error occurred',
47-
'detail' => $messages ? implode("\n", $messages) : '',
48-
'violations' => $violations,
51+
$result = array(
52+
'type' => $context['type'] ?? 'https://symfony.com/errors/validation',
53+
'title' => $context['title'] ?? 'Validation Failed',
4954
);
55+
if (isset($context['status'])) {
56+
$result['status'] = $context['status'];
57+
}
58+
if ($messages) {
59+
$result['detail'] = implode("\n", $messages);
60+
}
61+
if (isset($context['instance'])) {
62+
$result['instance'] = $context['instance'];
63+
}
64+
65+
return $result + array('violations' => $violations);
5066
}
5167

5268
/**

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/errors/validation',
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+
'title' => 'a',
54+
'type' => 'urn:uuid:f',
5455
),
5556
array(
5657
'propertyPath' => '4',
57-
'message' => '1',
58-
'code' => '6',
58+
'title' => '1',
59+
'type' => 'urn:uuid:6',
5960
),
6061
),
6162
);

0 commit comments

Comments
 (0)