-
-
Notifications
You must be signed in to change notification settings - Fork 962
Expand file tree
/
Copy pathItemNormalizer.php
More file actions
232 lines (199 loc) · 10.1 KB
/
ItemNormalizer.php
File metadata and controls
232 lines (199 loc) · 10.1 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
<?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\GraphQl\Serializer;
use ApiPlatform\GraphQl\State\Provider\NoopProvider;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\GraphQl\Query;
use ApiPlatform\Metadata\GraphQl\QueryCollection;
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
use ApiPlatform\Metadata\IriConverterInterface;
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\Util\ClassInfoTrait;
use ApiPlatform\Serializer\CacheKeyTrait;
use ApiPlatform\Serializer\ItemNormalizer as BaseItemNormalizer;
use Doctrine\Common\Collections\Collection;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
/**
* GraphQL normalizer.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class ItemNormalizer extends BaseItemNormalizer
{
use CacheKeyTrait;
use ClassInfoTrait;
public const FORMAT = 'graphql';
public const ITEM_RESOURCE_CLASS_KEY = '#itemResourceClass';
public const ITEM_IDENTIFIERS_KEY = '#itemIdentifiers';
private array $safeCacheKeysCache = [];
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, private readonly IdentifiersExtractorInterface $identifiersExtractor, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $logger ?: new NullLogger(), $resourceMetadataCollectionFactory, $resourceAccessChecker);
}
/**
* {@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}
*
* @param array<string, mixed> $context
*
* @throws UnexpectedValueException
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($data);
if ($this->getOutputClass($context)) {
$context['graphql_identifiers'] = [
self::ITEM_RESOURCE_CLASS_KEY => $context['operation']->getClass(),
self::ITEM_IDENTIFIERS_KEY => $this->identifiersExtractor->getIdentifiersFromItem($data, $context['operation'] ?? null),
];
return parent::normalize($data, $format, $context);
}
if ($this->isCacheKeySafe($context)) {
$context['cache_key'] = $this->getCacheKey($format, $context);
} else {
$context['cache_key'] = false;
}
unset($context['operation_name'], $context['operation']); // Remove operation and operation_name only when cache key has been created
$normalizedData = parent::normalize($data, $format, $context);
if (!\is_array($normalizedData)) {
throw new UnexpectedValueException('Expected data to be an array.');
}
if (isset($context['graphql_identifiers'])) {
$normalizedData += $context['graphql_identifiers'];
} elseif (!($context['no_resolver_data'] ?? false)) {
$normalizedData[self::ITEM_RESOURCE_CLASS_KEY] = $resourceClass;
$normalizedData[self::ITEM_IDENTIFIERS_KEY] = $this->identifiersExtractor->getIdentifiersFromItem($data, $context['operation'] ?? null);
}
if (isset($context['graphql_operation_name']) && 'mercure_subscription' === $context['graphql_operation_name'] && \is_object($data) && isset($normalizedData['id']) && !isset($normalizedData['_id'])) {
$normalizedData['_id'] = $normalizedData['id'];
$normalizedData['id'] = $this->iriConverter->getIriFromResource($data);
}
return $normalizedData;
}
/**
* {@inheritdoc}
*/
protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
{
// check for nested collection
$operation = $this->resourceMetadataCollectionFactory?->create($resourceClass)->getOperation(forceCollection: true, forceGraphQl: true);
if ($operation instanceof Query && $operation->getNested() && !$operation->getResolver() && (!$operation->getProvider() || NoopProvider::class === $operation->getProvider())) {
return [...$attributeValue];
}
// Handle relationships for mercure subscriptions
if ($operation instanceof QueryCollection && 'mercure_subscription' === $context['graphql_operation_name'] && $attributeValue instanceof Collection && !$attributeValue->isEmpty()) {
$relationContext = $context;
$relationContext['attributes'] = $context['attributes']['collection'];
$data['collection'] = [];
foreach ($attributeValue as $item) {
$data['collection'][] = $this->normalize($item, $format, $relationContext);
}
return $this->addPagination($attributeValue->count(), $data, $context);
}
// to-many are handled directly by the GraphQL resolver
return [];
}
private function addPagination(int $totalCount, array $data, array $context): array
{
if ($context['attributes']['paginationInfo'] ?? false) {
$data['paginationInfo'] = [];
if (\array_key_exists('hasNextPage', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['hasNextPage'] = $totalCount > ($context['pagination']['itemsPerPage'] ?? 10);
}
if (\array_key_exists('itemsPerPage', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['itemsPerPage'] = $context['pagination']['itemsPerPage'] ?? 10;
}
if (\array_key_exists('lastPage', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['lastPage'] = (int) ceil($totalCount / ($context['pagination']['itemsPerPage'] ?? 10));
}
if (\array_key_exists('totalCount', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['totalCount'] = $totalCount;
}
}
return $data;
}
/**
* {@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}
*/
protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
{
$allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
if (($context['api_denormalize'] ?? false) && \is_array($allowedAttributes) && false !== ($indexId = array_search('id', $allowedAttributes, true))) {
$allowedAttributes[] = '_id';
array_splice($allowedAttributes, (int) $indexId, 1);
}
return $allowedAttributes;
}
/**
* {@inheritdoc}
*/
protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
{
if ('_id' === $attribute) {
$attribute = 'id';
}
parent::setAttributeValue($object, $attribute, $value, $format, $context);
}
/**
* Check if any property contains a security grants, which makes the cache key not safe,
* as allowed_properties can differ for 2 instances of the same object.
*/
private function isCacheKeySafe(array $context): bool
{
if (!isset($context['resource_class']) || !$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
return false;
}
$resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']);
if (isset($this->safeCacheKeysCache[$resourceClass])) {
return $this->safeCacheKeysCache[$resourceClass];
}
$options = $this->getFactoryOptions($context);
$propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
$this->safeCacheKeysCache[$resourceClass] = true;
foreach ($propertyNames as $propertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
if (null !== $propertyMetadata->getSecurity()) {
$this->safeCacheKeysCache[$resourceClass] = false;
break;
}
}
return $this->safeCacheKeysCache[$resourceClass];
}
}