1 | <?php |
||
2 | |||
3 | /* |
||
4 | * This file is part of the API Platform project. |
||
5 | * |
||
6 | * (c) Kévin Dunglas <[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 | declare(strict_types=1); |
||
13 | |||
14 | namespace ApiPlatform\Core\Hal\Serializer; |
||
15 | |||
16 | use ApiPlatform\Core\Serializer\AbstractItemNormalizer; |
||
17 | use ApiPlatform\Core\Serializer\ContextTrait; |
||
18 | use ApiPlatform\Core\Util\ClassInfoTrait; |
||
19 | use Symfony\Component\Serializer\Exception\LogicException; |
||
20 | use Symfony\Component\Serializer\Exception\UnexpectedValueException; |
||
21 | use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface; |
||
22 | |||
23 | /** |
||
24 | * Converts between objects and array including HAL metadata. |
||
25 | * |
||
26 | * @author Kévin Dunglas <[email protected]> |
||
27 | */ |
||
28 | final class ItemNormalizer extends AbstractItemNormalizer |
||
29 | { |
||
30 | use ContextTrait; |
||
31 | use ClassInfoTrait; |
||
32 | |||
33 | public const FORMAT = 'jsonhal'; |
||
34 | |||
35 | private $componentsCache = []; |
||
36 | private $attributesMetadataCache = []; |
||
37 | |||
38 | /** |
||
39 | * {@inheritdoc} |
||
40 | */ |
||
41 | public function supportsNormalization($data, $format = null): bool |
||
42 | { |
||
43 | return self::FORMAT === $format && parent::supportsNormalization($data, $format); |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * {@inheritdoc} |
||
48 | */ |
||
49 | public function normalize($object, $format = null, array $context = []) |
||
50 | { |
||
51 | if (null !== $this->getOutputClass($this->getObjectClass($object), $context)) { |
||
52 | return parent::normalize($object, $format, $context); |
||
53 | } |
||
54 | |||
55 | if (!isset($context['cache_key'])) { |
||
56 | $context['cache_key'] = $this->getHalCacheKey($format, $context); |
||
57 | } |
||
58 | |||
59 | $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null); |
||
60 | $context = $this->initContext($resourceClass, $context); |
||
61 | $iri = $this->iriConverter->getIriFromItem($object); |
||
62 | $context['iri'] = $iri; |
||
63 | $context['api_normalize'] = true; |
||
64 | |||
65 | $data = parent::normalize($object, $format, $context); |
||
66 | if (!\is_array($data)) { |
||
67 | return $data; |
||
68 | } |
||
69 | |||
70 | $metadata = [ |
||
71 | '_links' => [ |
||
72 | 'self' => [ |
||
73 | 'href' => $iri, |
||
74 | ], |
||
75 | ], |
||
76 | ]; |
||
77 | $components = $this->getComponents($object, $format, $context); |
||
78 | $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'links'); |
||
79 | $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'embedded'); |
||
80 | |||
81 | return $metadata + $data; |
||
82 | } |
||
83 | |||
84 | /** |
||
85 | * {@inheritdoc} |
||
86 | */ |
||
87 | public function supportsDenormalization($data, $type, $format = null): bool |
||
88 | { |
||
89 | // prevent the use of lower priority normalizers (e.g. serializer.normalizer.object) for this format |
||
90 | return self::FORMAT === $format; |
||
91 | } |
||
92 | |||
93 | /** |
||
94 | * {@inheritdoc} |
||
95 | * |
||
96 | * @throws LogicException |
||
97 | */ |
||
98 | public function denormalize($data, $class, $format = null, array $context = []) |
||
99 | { |
||
100 | throw new LogicException(sprintf('%s is a read-only format.', self::FORMAT)); |
||
101 | } |
||
102 | |||
103 | /** |
||
104 | * {@inheritdoc} |
||
105 | */ |
||
106 | protected function getAttributes($object, $format = null, array $context): array |
||
107 | { |
||
108 | return $this->getComponents($object, $format, $context)['states']; |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * Gets HAL components of the resource: states, links and embedded. |
||
113 | * |
||
114 | * @param object $object |
||
115 | */ |
||
116 | private function getComponents($object, ?string $format, array $context): array |
||
117 | { |
||
118 | $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key']; |
||
119 | |||
120 | if (isset($this->componentsCache[$cacheKey])) { |
||
121 | return $this->componentsCache[$cacheKey]; |
||
122 | } |
||
123 | |||
124 | $attributes = parent::getAttributes($object, $format, $context); |
||
125 | $options = $this->getFactoryOptions($context); |
||
126 | |||
127 | $components = [ |
||
128 | 'states' => [], |
||
129 | 'links' => [], |
||
130 | 'embedded' => [], |
||
131 | ]; |
||
132 | |||
133 | foreach ($attributes as $attribute) { |
||
134 | $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options); |
||
135 | |||
136 | $type = $propertyMetadata->getType(); |
||
137 | $isOne = $isMany = false; |
||
138 | |||
139 | if (null !== $type) { |
||
140 | if ($type->isCollection()) { |
||
141 | $valueType = $type->getCollectionValueType(); |
||
142 | $isMany = null !== $valueType && ($className = $valueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className); |
||
143 | } else { |
||
144 | $className = $type->getClassName(); |
||
145 | $isOne = $className && $this->resourceClassResolver->isResourceClass($className); |
||
146 | } |
||
147 | } |
||
148 | |||
149 | if (!$isOne && !$isMany) { |
||
150 | $components['states'][] = $attribute; |
||
151 | continue; |
||
152 | } |
||
153 | |||
154 | $relation = ['name' => $attribute, 'cardinality' => $isOne ? 'one' : 'many']; |
||
155 | if ($propertyMetadata->isReadableLink()) { |
||
156 | $components['embedded'][] = $relation; |
||
157 | } |
||
158 | |||
159 | $components['links'][] = $relation; |
||
160 | } |
||
161 | |||
162 | if (false !== $context['cache_key']) { |
||
163 | $this->componentsCache[$cacheKey] = $components; |
||
164 | } |
||
165 | |||
166 | return $components; |
||
167 | } |
||
168 | |||
169 | /** |
||
170 | * Populates _links and _embedded keys. |
||
171 | * |
||
172 | * @param object $object |
||
173 | */ |
||
174 | private function populateRelation(array $data, $object, ?string $format, array $context, array $components, string $type): array |
||
175 | { |
||
176 | $class = $this->getObjectClass($object); |
||
177 | |||
178 | $attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ? |
||
179 | $this->attributesMetadataCache[$class] : |
||
180 | $this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null; |
||
181 | |||
182 | $key = '_'.$type; |
||
183 | foreach ($components[$type] as $relation) { |
||
184 | if (null !== $attributesMetadata && $this->isMaxDepthReached($attributesMetadata, $class, $relation['name'], $context)) { |
||
185 | continue; |
||
186 | } |
||
187 | |||
188 | $attributeValue = $this->getAttributeValue($object, $relation['name'], $format, $context); |
||
189 | if (empty($attributeValue)) { |
||
190 | continue; |
||
191 | } |
||
192 | |||
193 | $relationName = $relation['name']; |
||
194 | if ($this->nameConverter) { |
||
195 | $relationName = $this->nameConverter->normalize($relationName, $class, $format, $context); |
||
0 ignored issues
–
show
|
|||
196 | } |
||
197 | |||
198 | if ('one' === $relation['cardinality']) { |
||
199 | if ('links' === $type) { |
||
200 | $data[$key][$relationName]['href'] = $this->getRelationIri($attributeValue); |
||
201 | continue; |
||
202 | } |
||
203 | |||
204 | $data[$key][$relationName] = $attributeValue; |
||
205 | continue; |
||
206 | } |
||
207 | |||
208 | // many |
||
209 | $data[$key][$relationName] = []; |
||
210 | foreach ($attributeValue as $rel) { |
||
211 | if ('links' === $type) { |
||
212 | $rel = ['href' => $this->getRelationIri($rel)]; |
||
213 | } |
||
214 | |||
215 | $data[$key][$relationName][] = $rel; |
||
216 | } |
||
217 | } |
||
218 | |||
219 | return $data; |
||
220 | } |
||
221 | |||
222 | /** |
||
223 | * Gets the IRI of the given relation. |
||
224 | * |
||
225 | * @throws UnexpectedValueException |
||
226 | */ |
||
227 | private function getRelationIri($rel): string |
||
228 | { |
||
229 | if (!(\is_array($rel) || \is_string($rel))) { |
||
230 | throw new UnexpectedValueException('Expected relation to be an IRI or array'); |
||
231 | } |
||
232 | |||
233 | return \is_string($rel) ? $rel : $rel['_links']['self']['href']; |
||
234 | } |
||
235 | |||
236 | /** |
||
237 | * Gets the cache key to use. |
||
238 | * |
||
239 | * @return bool|string |
||
240 | */ |
||
241 | private function getHalCacheKey(?string $format, array $context) |
||
242 | { |
||
243 | try { |
||
244 | return md5($format.serialize($context)); |
||
245 | } catch (\Exception $exception) { |
||
246 | // The context cannot be serialized, skip the cache |
||
247 | return false; |
||
248 | } |
||
249 | } |
||
250 | |||
251 | /** |
||
252 | * Is the max depth reached for the given attribute? |
||
253 | * |
||
254 | * @param AttributeMetadataInterface[] $attributesMetadata |
||
255 | */ |
||
256 | private function isMaxDepthReached(array $attributesMetadata, string $class, string $attribute, array &$context): bool |
||
257 | { |
||
258 | if ( |
||
259 | !($context[self::ENABLE_MAX_DEPTH] ?? false) || |
||
260 | !isset($attributesMetadata[$attribute]) || |
||
261 | null === $maxDepth = $attributesMetadata[$attribute]->getMaxDepth() |
||
262 | ) { |
||
263 | return false; |
||
264 | } |
||
265 | |||
266 | $key = sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute); |
||
267 | if (!isset($context[$key])) { |
||
268 | $context[$key] = 1; |
||
269 | |||
270 | return false; |
||
271 | } |
||
272 | |||
273 | if ($context[$key] === $maxDepth) { |
||
274 | return true; |
||
275 | } |
||
276 | |||
277 | ++$context[$key]; |
||
278 | |||
279 | return false; |
||
280 | } |
||
281 | } |
||
282 |
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.