-
-
Notifications
You must be signed in to change notification settings - Fork 962
Expand file tree
/
Copy pathItemNormalizer.php
More file actions
255 lines (222 loc) · 11.7 KB
/
ItemNormalizer.php
File metadata and controls
255 lines (222 loc) · 11.7 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
<?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\JsonLd\Serializer;
use ApiPlatform\Hydra\Serializer\HydraOperationsTrait;
use ApiPlatform\JsonLd\AnonymousContextBuilderInterface;
use ApiPlatform\JsonLd\ContextBuilderInterface;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Operation\Factory\OperationMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\Serializer\AbstractItemNormalizer;
use ApiPlatform\Serializer\ContextTrait;
use ApiPlatform\Serializer\OperationResourceClassResolverInterface;
use ApiPlatform\Serializer\TagCollectorInterface;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
/**
* Converts between objects and array including JSON-LD and Hydra metadata.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class ItemNormalizer extends AbstractItemNormalizer
{
use ClassInfoTrait;
use ContextTrait;
use HydraOperationsTrait;
use HydraPrefixTrait;
use JsonLdContextTrait;
public const FORMAT = 'jsonld';
private const JSONLD_KEYWORDS = [
'@context',
'@direction',
'@graph',
'@id',
'@import',
'@included',
'@index',
'@json',
'@language',
'@list',
'@nest',
'@none',
'@prefix',
'@propagate',
'@protected',
'@reverse',
'@set',
'@type',
'@value',
'@version',
'@vocab',
];
private array $itemNormalizerDefaultContext = [];
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null, private ?OperationMetadataFactoryInterface $operationMetadataFactory = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null)
{
$this->itemNormalizerDefaultContext = $defaultContext;
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver);
}
/**
* {@inheritdoc}
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array
{
return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
}
/**
* {@inheritdoc}
*
* @throws LogicException
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($data);
$outputClass = $this->getOutputClass($context);
if ($outputClass && !($context['item_uri_template'] ?? null)) {
return parent::normalize($data, $format, $context);
}
// TODO: we should not remove the resource_class in the normalizeRawCollection as we would find out anyway that it's not the same as the requested one
$previousResourceClass = $context['resource_class'] ?? null;
$metadata = [];
if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
$resourceClass = $this->resourceClassResolver->getResourceClass($data, $previousResourceClass);
if (isset($context['operation']) && $context['operation'] instanceof HttpOperation && $context['operation']->getClass() !== $resourceClass) {
$context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(null, false, true);
}
$context = $this->initContext($resourceClass, $context);
$metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
} elseif ($this->contextBuilder instanceof AnonymousContextBuilderInterface) {
if ($context['api_collection_sub_level'] ?? false) {
unset($context['api_collection_sub_level']);
$context['output']['gen_id'] ??= true;
$context['output']['iri'] = null;
}
if (isset($context['item_uri_template']) && $this->operationMetadataFactory) {
$context['output']['operation'] = $this->operationMetadataFactory->create($context['item_uri_template']);
} elseif ($this->resourceClassResolver->isResourceClass($resourceClass)) {
$context['output']['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
}
// We should improve what's behind the context creation, its probably more complicated then it should
$metadata = $this->createJsonLdContext($this->contextBuilder, $data, $context);
}
// Special case: non-resource got serialized and contains a resource therefore we need to reset part of the context
if ($previousResourceClass !== $resourceClass && $resourceClass !== $outputClass) {
unset($context['operation'], $context['operation_name'], $context['output']);
}
if (true === ($context['output']['gen_id'] ?? true) && true === ($context['force_iri_generation'] ?? true) && $iri = $this->iriConverter->getIriFromResource($data, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context)) {
$context['iri'] = $iri;
$metadata['@id'] = $iri;
}
$context['api_normalize'] = true;
$normalizedData = parent::normalize($data, $format, $context);
if (!\is_array($normalizedData)) {
return $normalizedData;
}
$operation = $context['operation'] ?? null;
if ($this->operationMetadataFactory && isset($context['item_uri_template']) && !$operation) {
$operation = $this->operationMetadataFactory->create($context['item_uri_template']);
}
if ($isResourceClass && !$operation) {
$operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
}
if (!isset($metadata['@type']) && $operation) {
$types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
if (null === $types) {
// TODO: 5.x break on this as this looks wrong, CollectionReferencingItem returns an IRI that point through
// ItemReferencedInCollection but it returns a CollectionReferencingItem therefore we should use the current
// object's class Type and not rely on operation ?
if (isset($context['item_uri_template'])) {
// When the operation comes from item_uri_template, use its shortName directly
// as $resourceClass refers to the collection resource, not the item resource
$types = [$operation->getShortName()];
} else {
// Use resource-level shortName to avoid operation-specific overrides
$typeClass = $isResourceClass ? $resourceClass : ($operation->getClass() ?? $resourceClass);
try {
$types = [$this->resourceMetadataCollectionFactory->create($typeClass)[0]->getShortName()];
} catch (\Exception) {
$types = [$operation->getShortName()];
}
}
}
$metadata['@type'] = 1 === \count($types) ? $types[0] : $types;
}
if ($isResourceClass) {
$showOperations = $context['hydra_operations'] ?? false;
if ($showOperations) {
$hydraOperations = $this->getHydraOperations(
false,
$this->resourceMetadataCollectionFactory->create($resourceClass)[0],
$this->getHydraPrefix($context + $this->itemNormalizerDefaultContext)
);
if (!empty($hydraOperations)) {
$metadata['operation'] = $hydraOperations;
}
}
}
return $metadata + $normalizedData;
}
/**
* {@inheritdoc}
*/
public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
{
return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
}
/**
* {@inheritdoc}
*
* @throws NotNormalizableValueException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
// Avoid issues with proxies if we populated the object
if (isset($data['@id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
if (true !== ($context['api_allow_update'] ?? true)) {
throw new NotNormalizableValueException('Update is not allowed for this operation.');
}
try {
$context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($data['@id'], $context + ['fetch_data' => true], $context['operation'] ?? null);
} catch (ItemNotFoundException $e) {
$operation = $context['operation'] ?? null;
if (!('PUT' === $operation?->getMethod() && ($operation->getExtraProperties()['standard_put'] ?? true))) {
throw $e;
}
}
}
return parent::denormalize($data, $type, $format, $context);
}
protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
{
$allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
if (\is_array($allowedAttributes) && ($context['api_denormalize'] ?? false)) {
$allowedAttributes = array_merge($allowedAttributes, self::JSONLD_KEYWORDS);
}
return $allowedAttributes;
}
}