forked from api-platform/core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItemNormalizer.php
More file actions
270 lines (222 loc) · 8.81 KB
/
ItemNormalizer.php
File metadata and controls
270 lines (222 loc) · 8.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Hal\Serializer;
use ApiPlatform\Api\UrlGeneratorInterface;
use ApiPlatform\Serializer\AbstractItemNormalizer;
use ApiPlatform\Serializer\CacheKeyTrait;
use ApiPlatform\Serializer\ContextTrait;
use ApiPlatform\Util\ClassInfoTrait;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
/**
* Converts between objects and array including HAL metadata.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class ItemNormalizer extends AbstractItemNormalizer
{
use CacheKeyTrait;
use ClassInfoTrait;
use ContextTrait;
public const FORMAT = 'jsonhal';
private array $componentsCache = [];
private array $attributesMetadataCache = [];
/**
* {@inheritdoc}
*/
public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
{
return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
}
/**
* {@inheritdoc}
*/
public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($object);
if ($this->getOutputClass($context)) {
return parent::normalize($object, $format, $context);
}
if (!isset($context['cache_key'])) {
$context['cache_key'] = $this->getCacheKey($format, $context);
}
if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
$resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
}
$context = $this->initContext($resourceClass, $context);
$iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
$context['iri'] = $iri;
$context['api_normalize'] = true;
$data = parent::normalize($object, $format, $context);
if (!\is_array($data)) {
return $data;
}
$metadata = [
'_links' => [
'self' => [
'href' => $iri,
],
],
];
$components = $this->getComponents($object, $format, $context);
$metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'links');
$metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'embedded');
return $metadata + $data;
}
/**
* {@inheritdoc}
*/
public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
{
// prevent the use of lower priority normalizers (e.g. serializer.normalizer.object) for this format
return self::FORMAT === $format;
}
/**
* {@inheritdoc}
*
* @throws LogicException
*/
public function denormalize(mixed $data, string $type, string $format = null, array $context = []): never
{
throw new LogicException(sprintf('%s is a read-only format.', self::FORMAT));
}
/**
* {@inheritdoc}
*/
protected function getAttributes($object, $format = null, array $context = []): array
{
return $this->getComponents($object, $format, $context)['states'];
}
/**
* Gets HAL components of the resource: states, links and embedded.
*/
private function getComponents(object $object, ?string $format, array $context): array
{
$cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
if (isset($this->componentsCache[$cacheKey])) {
return $this->componentsCache[$cacheKey];
}
$attributes = parent::getAttributes($object, $format, $context);
$options = $this->getFactoryOptions($context);
$components = [
'states' => [],
'links' => [],
'embedded' => [],
];
foreach ($attributes as $attribute) {
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
// TODO: 3.0 support multiple types, default value of types will be [] instead of null
$type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
$isOne = $isMany = false;
if (null !== $type) {
if ($type->isCollection()) {
$valueType = $type->getCollectionValueTypes()[0] ?? null;
$isMany = null !== $valueType && ($className = $valueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
} else {
$className = $type->getClassName();
$isOne = $className && $this->resourceClassResolver->isResourceClass($className);
}
}
if (!$isOne && !$isMany) {
$components['states'][] = $attribute;
continue;
}
$relation = ['name' => $attribute, 'cardinality' => $isOne ? 'one' : 'many'];
if ($propertyMetadata->isReadableLink()) {
$components['embedded'][] = $relation;
}
$components['links'][] = $relation;
}
if (false !== $context['cache_key']) {
$this->componentsCache[$cacheKey] = $components;
}
return $components;
}
/**
* Populates _links and _embedded keys.
*/
private function populateRelation(array $data, object $object, ?string $format, array $context, array $components, string $type): array
{
$class = $this->getObjectClass($object);
$attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ?
$this->attributesMetadataCache[$class] :
$this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null;
$key = '_'.$type;
foreach ($components[$type] as $relation) {
if (null !== $attributesMetadata && $this->isMaxDepthReached($attributesMetadata, $class, $relation['name'], $context)) {
continue;
}
$attributeValue = $this->getAttributeValue($object, $relation['name'], $format, $context);
if (empty($attributeValue)) {
continue;
}
$relationName = $relation['name'];
if ($this->nameConverter) {
$relationName = $this->nameConverter->normalize($relationName, $class, $format, $context);
}
if ('one' === $relation['cardinality']) {
if ('links' === $type) {
$data[$key][$relationName]['href'] = $this->getRelationIri($attributeValue);
continue;
}
$data[$key][$relationName] = $attributeValue;
continue;
}
// many
$data[$key][$relationName] = [];
foreach ($attributeValue as $rel) {
if ('links' === $type) {
$rel = ['href' => $this->getRelationIri($rel)];
}
$data[$key][$relationName][] = $rel;
}
}
return $data;
}
/**
* Gets the IRI of the given relation.
*
* @throws UnexpectedValueException
*/
private function getRelationIri(mixed $rel): string
{
if (!(\is_array($rel) || \is_string($rel))) {
throw new UnexpectedValueException('Expected relation to be an IRI or array');
}
return \is_string($rel) ? $rel : $rel['_links']['self']['href'];
}
/**
* Is the max depth reached for the given attribute?
*
* @param AttributeMetadataInterface[] $attributesMetadata
*/
private function isMaxDepthReached(array $attributesMetadata, string $class, string $attribute, array &$context): bool
{
if (
!($context[self::ENABLE_MAX_DEPTH] ?? false) ||
!isset($attributesMetadata[$attribute]) ||
null === $maxDepth = $attributesMetadata[$attribute]->getMaxDepth()
) {
return false;
}
$key = sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute);
if (!isset($context[$key])) {
$context[$key] = 1;
return false;
}
if ($context[$key] === $maxDepth) {
return true;
}
++$context[$key];
return false;
}
}