Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/ConstraintViolationListNormalizer.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Serializer\Normalizer;
13
14 use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
15 use Symfony\Component\Validator\ConstraintViolationListInterface;
16
17 /**
18 * A normalizer that normalizes a ConstraintViolationListInterface instance.
19 *
20 * This Normalizer implements RFC7807 {@link https://tools.ietf.org/html/rfc7807}.
21 *
22 * @author Grégoire Pineau <[email protected]>
23 * @author Kévin Dunglas <[email protected]>
24 */
25 final class ConstraintViolationListNormalizer implements NormalizerInterface
26 {
27 public const INSTANCE = 'instance';
28 public const STATUS = 'status';
29 public const TITLE = 'title';
30 public const TYPE = 'type';
31 public const PAYLOAD_FIELDS = 'payload_fields';
32
33 public function __construct(
34 private readonly array $defaultContext = [],
35 private readonly ?NameConverterInterface $nameConverter = null,
36 ) {
37 }
38
39 public function getSupportedTypes(?string $format): array
40 {
41 return [
42 ConstraintViolationListInterface::class => true,
43 ];
44 }
45
46 public function normalize(mixed $data, ?string $format = null, array $context = []): array
47 {
48 if (\array_key_exists(self::PAYLOAD_FIELDS, $context)) {
49 $payloadFieldsToSerialize = $context[self::PAYLOAD_FIELDS];
50 } elseif (\array_key_exists(self::PAYLOAD_FIELDS, $this->defaultContext)) {
51 $payloadFieldsToSerialize = $this->defaultContext[self::PAYLOAD_FIELDS];
52 } else {
53 $payloadFieldsToSerialize = [];
54 }
55
56 if (\is_array($payloadFieldsToSerialize) && [] !== $payloadFieldsToSerialize) {
57 $payloadFieldsToSerialize = array_flip($payloadFieldsToSerialize);
58 }
59
60 $violations = [];
61 $messages = [];
62 foreach ($data as $violation) {
63 $propertyPath = $violation->getPropertyPath();
64
65 if (null !== $this->nameConverter) {
66 $propertyPath = $this->normalizePropertyPath($propertyPath, \is_object($violation->getRoot()) ? \get_class($violation->getRoot()) : null, $format, $context);
67 }
68
69 $violationEntry = [
70 'propertyPath' => $propertyPath,
71 'title' => $violation->getMessage(),
72 'template' => $violation->getMessageTemplate(),
73 'parameters' => $violation->getParameters(),
74 ];
75 if (null !== $code = $violation->getCode()) {
76 $violationEntry['type'] = \sprintf('urn:uuid:%s', $code);
77 }
78
79 $constraint = $violation->getConstraint();
80 if (
81 [] !== $payloadFieldsToSerialize
82 && $constraint
83 && $constraint->payload
84 // If some or all payload fields are whitelisted, add them
85 && $payloadFields = null === $payloadFieldsToSerialize || true === $payloadFieldsToSerialize ? $constraint->payload : array_intersect_key($constraint->payload, $payloadFieldsToSerialize)
86 ) {
87 $violationEntry['payload'] = $payloadFields;
88 }
89
90 $violations[] = $violationEntry;
91
92 $prefix = $propertyPath ? \sprintf('%s: ', $propertyPath) : '';
93 $messages[] = $prefix.$violation->getMessage();
94 }
95
96 $result = [
97 'type' => $context[self::TYPE] ?? $this->defaultContext[self::TYPE] ?? 'https://symfony.com/errors/validation',
98 'title' => $context[self::TITLE] ?? $this->defaultContext[self::TITLE] ?? 'Validation Failed',
99 ];
100 if (null !== $status = ($context[self::STATUS] ?? $this->defaultContext[self::STATUS] ?? null)) {
101 $result['status'] = $status;
102 }
103 if ($messages) {
104 $result['detail'] = implode("\n", $messages);
105 }
106 if (null !== $instance = ($context[self::INSTANCE] ?? $this->defaultContext[self::INSTANCE] ?? null)) {
107 $result['instance'] = $instance;
108 }
109
110 return $result + ['violations' => $violations];
111 }
112
113 private function normalizePropertyPath(string $propertyPath, ?string $class, ?string $format, array $context): string
114 {
115 if (!str_contains($propertyPath, '.')) {
116 return $this->nameConverter->normalize($propertyPath, $class, $format, $context);
117 }
118
119 $result = [];
120 $currentClass = $class;
121
122 foreach (explode('.', $propertyPath) as $segment) {
123 $subscript = '';
124 $propertyName = $segment;
125 if (false !== $bracketPos = strpos($segment, '[')) {
126 $propertyName = substr($segment, 0, $bracketPos);
127 $subscript = substr($segment, $bracketPos);
128 }
129
130 $result[] = $this->nameConverter->normalize($propertyName, $currentClass, $format, $context).$subscript;
131
132 $currentClass = $this->getPropertyClassFromReflection($currentClass, $propertyName);
133 }
134
135 return implode('.', $result);
136 }
137
138 private function getPropertyClassFromReflection(?string $class, string $property): ?string
139 {
140 if (null === $class) {
141 return null;
142 }
143
144 try {
145 $type = (new \ReflectionProperty($class, $property))->getType();
146 if ($type instanceof \ReflectionNamedType && !$type->isBuiltin()) {
147 return $type->getName();
148 }
149 } catch (\ReflectionException) {
150 }
151
152 return null;
153 }
154
155 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
156 {
157 return $data instanceof ConstraintViolationListInterface;
158 }
159 }