-
-
Notifications
You must be signed in to change notification settings - Fork 905
Expand file tree
/
Copy pathJMSModelDescriber.php
More file actions
430 lines (358 loc) · 14.8 KB
/
Copy pathJMSModelDescriber.php
File metadata and controls
430 lines (358 loc) · 14.8 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
<?php
/*
* This file is part of the NelmioApiDocBundle package.
*
* (c) Nelmio
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nelmio\ApiDocBundle\ModelDescriber;
use JMS\Serializer\Context;
use JMS\Serializer\ContextFactory\SerializationContextFactoryInterface;
use JMS\Serializer\Exclusion\GroupsExclusionStrategy;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
use JMS\Serializer\SerializationContext;
use Metadata\MetadataFactoryInterface;
use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareInterface;
use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareTrait;
use Nelmio\ApiDocBundle\Model\Model;
use Nelmio\ApiDocBundle\ModelDescriber\Annotations\AnnotationsReader;
use Nelmio\ApiDocBundle\OpenApiPhp\Util;
use Nelmio\ApiDocBundle\Util\LegacyTypeConverter;
use OpenApi\Annotations as OA;
use OpenApi\Generator;
use Symfony\Component\TypeInfo\Type\ObjectType;
/**
* Uses the JMS metadata factory to extract input/output model information.
*/
class JMSModelDescriber implements ModelDescriberInterface, ModelRegistryAwareInterface
{
use ApplyOpenApiDiscriminatorTrait;
use ModelRegistryAwareTrait;
private MetadataFactoryInterface $factory;
private ?SerializationContextFactoryInterface $contextFactory;
private ?PropertyNamingStrategyInterface $namingStrategy;
/**
* @var array<string, Context>
*/
private array $contexts = [];
/**
* @var array<string, \SplStack>
*/
private array $metadataStacks = [];
/**
* @var string[]
*/
private array $mediaTypes;
/**
* @var array<string, bool|null>
*/
private array $propertyTypeUseGroupsCache = [];
private bool $useValidationGroups;
/**
* @param string[] $mediaTypes
*/
public function __construct(
MetadataFactoryInterface $factory,
array $mediaTypes,
?PropertyNamingStrategyInterface $namingStrategy = null,
bool $useValidationGroups = false,
?SerializationContextFactoryInterface $contextFactory = null,
) {
$this->factory = $factory;
$this->namingStrategy = $namingStrategy;
$this->mediaTypes = $mediaTypes;
$this->useValidationGroups = $useValidationGroups;
$this->contextFactory = $contextFactory;
}
public function describe(Model $model, OA\Schema $schema): void
{
$type = $model->getTypeInfo();
if (!$type instanceof ObjectType) {
return;
}
$className = $type->getClassName();
$metadata = $this->factory->getMetadataForClass($className);
if (!$metadata instanceof ClassMetadata) {
throw new \InvalidArgumentException(\sprintf('No metadata found for class %s.', $className));
}
if (null !== $metadata->discriminatorFieldName
&& $className === $metadata->discriminatorBaseClass
&& [] !== $metadata->discriminatorMap
&& Generator::UNDEFINED === $schema->discriminator) {
$this->applyOpenApiDiscriminator(
$model,
$schema,
$this->modelRegistry,
$metadata->discriminatorFieldName,
$metadata->discriminatorMap
);
return;
}
$annotationsReader = new AnnotationsReader(
$this->modelRegistry,
$this->mediaTypes,
$this->useValidationGroups
);
$classResult = $annotationsReader->updateDefinition(new \ReflectionClass($className), $schema);
if (!$classResult) {
return;
}
$schema->type = 'object';
$isJmsV1 = null !== $this->namingStrategy;
$context = $this->getSerializationContext($model);
$context->pushClassMetadata($metadata);
foreach ($metadata->propertyMetadata as $item) {
// filter groups
if (null !== $context->getExclusionStrategy() && $context->getExclusionStrategy()->shouldSkipProperty($item, $context)) {
continue;
}
$context->pushPropertyMetadata($item);
$name = true === $isJmsV1 ? $this->namingStrategy->translateName($item) : $item->serializedName;
// read property options from Swagger Property attribute if it exists
$reflections = [];
if (true === $isJmsV1 && property_exists($item, 'reflection') && null !== $item->reflection) {
$reflections[] = $item->reflection;
} elseif (property_exists($item->class, $item->name)) {
$reflections[] = new \ReflectionProperty($item->class, $item->name);
}
if (null !== $item->getter) {
try {
$reflections[] = new \ReflectionMethod($item->class, $item->getter);
} catch (\ReflectionException) {
}
}
if (null !== $item->setter) {
try {
$reflections[] = new \ReflectionMethod($item->class, $item->setter);
} catch (\ReflectionException) {
}
}
if (!$annotationsReader->shouldDescribeProperty($reflections)) {
$context->popPropertyMetadata();
continue;
}
$groups = $this->computeGroups($context, $item->type);
if (true === $item->inline && isset($item->type['name'])) {
// currently array types can not be documented :-/
if (!\in_array($item->type['name'], ['array', 'ArrayCollection'], true)) {
$inlineModel = new Model(LegacyTypeConverter::createType($item->type['name']), $groups);
$this->describe($inlineModel, $schema);
}
$context->popPropertyMetadata();
continue;
}
foreach ($reflections as $reflection) {
$name = $annotationsReader->getPropertyName($reflection, $name);
}
$property = Util::getProperty($schema, $name);
foreach ($reflections as $reflection) {
$annotationsReader->updateProperty($reflection, $property, $groups);
}
if (Generator::UNDEFINED !== $property->type || Generator::UNDEFINED !== $property->ref) {
$context->popPropertyMetadata();
continue;
}
if (Generator::UNDEFINED === $property->default && $item->hasDefault) {
$property->default = $item->defaultValue;
}
if (null === $item->type) {
$key = Util::searchIndexedCollectionItem($schema->properties, 'property', $name);
unset($schema->properties[$key]);
$context->popPropertyMetadata();
continue;
}
$this->describeItem($item->type, $property, $context, $model->getSerializationContext());
$context->popPropertyMetadata();
}
$context->popClassMetadata();
}
/**
* @internal
*/
public function getSerializationContext(Model $model): Context
{
if (isset($this->contexts[$model->getHash()])) {
$context = $this->contexts[$model->getHash()];
$stack = $context->getMetadataStack();
while (!$stack->isEmpty()) {
$stack->pop();
}
foreach ($this->metadataStacks[$model->getHash()] as $metadataCopy) {
$stack->unshift($metadataCopy);
}
} else {
$context = null !== $this->contextFactory
? $this->contextFactory->createSerializationContext()
: SerializationContext::create();
if (null !== $model->getGroups()) {
$context->addExclusionStrategy(new GroupsExclusionStrategy($model->getGroups()));
}
}
return $context;
}
/**
* @param mixed[]|null $type
*
* @return string[]|null
*/
private function computeGroups(Context $context, ?array $type = null): ?array
{
if (null === $type || true !== $this->propertyTypeUsesGroups($type)) {
return null;
}
$groupsExclusion = $context->getExclusionStrategy();
if (!$groupsExclusion instanceof GroupsExclusionStrategy) {
return null;
}
$groups = $groupsExclusion->getGroupsFor($context);
if ([GroupsExclusionStrategy::DEFAULT_GROUP] === $groups) {
return null;
}
return $groups;
}
public function supports(Model $model): bool
{
if (($model->getSerializationContext()['useJms'] ?? null) === false) {
return false;
}
$type = $model->getTypeInfo();
if (!$type instanceof ObjectType) {
return false;
}
$className = $type->getClassName();
try {
if (null !== $this->factory->getMetadataForClass($className)) {
return true;
}
} catch (\ReflectionException) {
}
return false;
}
/**
* @internal
*
* @param mixed[] $type
* @param mixed[] $serializationContext
*/
public function describeItem(array $type, OA\Schema $property, Context $context, array $serializationContext): void
{
$nestedTypeInfo = $this->getNestedTypeInArray($type);
if (null !== $nestedTypeInfo) {
[$nestedType, $isHash] = $nestedTypeInfo;
if ($isHash) {
$property->type = 'object';
$property->additionalProperties = Util::createChild($property, OA\AdditionalProperties::class);
// this is a free form object (as nested array)
if ('array' === $nestedType['name'] && !isset($nestedType['params'][0])) {
// in the case of a virtual property, set it as free object type
$property->additionalProperties = true;
return;
}
$this->describeItem($nestedType, $property->additionalProperties, $context, $serializationContext);
return;
}
$property->type = 'array';
$property->items = Util::createChild($property, OA\Items::class);
$this->describeItem($nestedType, $property->items, $context, $serializationContext);
} elseif ('array' === $type['name']) {
$property->type = 'object';
$property->additionalProperties = true;
} elseif ('string' === $type['name']) {
$property->type = 'string';
} elseif (\in_array($type['name'], ['bool', 'boolean'], true)) {
$property->type = 'boolean';
} elseif (\in_array($type['name'], ['int', 'integer'], true)) {
$property->type = 'integer';
} elseif (\in_array($type['name'], ['double', 'float'], true)) {
$property->type = 'number';
$property->format = $type['name'];
} elseif (is_a($type['name'], \DateTimeInterface::class, true)) {
$property->type = 'string';
$property->format = 'date-time';
} else {
// See https://github.com/schmittjoh/serializer/blob/5a5a03a/src/Metadata/Driver/EnumPropertiesDriver.php#L51
if ('enum' === $type['name']
&& isset($type['params'][0])
) {
$typeParam = $type['params'][0];
if (isset($typeParam['name'])) {
$typeParam = $typeParam['name'];
}
if (\is_string($typeParam) && enum_exists($typeParam)) {
$type['name'] = $typeParam;
}
if (isset($type['params'][1])) {
if ('value' !== $type['params'][1] && is_a($type['name'], \BackedEnum::class, true)) {
// In case of a backed enum, it is possible to serialize it using its names instead of values
// Set a specific serialization context property to enforce a new model, as options cannot be used to force a new model
// See https://github.com/schmittjoh/serializer/blob/5a5a03a71a28a480189c5a0ca95893c19f1d120c/src/Handler/EnumHandler.php#L47
$serializationContext[EnumModelDescriber::FORCE_NAMES] = true;
}
}
}
$groups = $this->computeGroups($context, $type);
unset($serializationContext['groups']);
$model = new Model(LegacyTypeConverter::createType($type['name']), $groups, [], $serializationContext);
$modelRef = $this->modelRegistry->register($model);
$customFields = (array) $property->jsonSerialize();
unset(
$customFields['property'],
$customFields['nullable'],
);
if ([] === $customFields) { // no custom fields
$property->ref = $modelRef;
} else {
$weakContext = Util::createWeakContext($property->_context);
$property->oneOf = [new OA\Schema(['ref' => $modelRef, '_context' => $weakContext])];
}
$this->contexts[$model->getHash()] = $context;
$this->metadataStacks[$model->getHash()] = clone $context->getMetadataStack();
}
}
/**
* @param mixed[] $type
*
* @return array{0: mixed, 1: bool}|null
*/
private function getNestedTypeInArray(array $type): ?array
{
if ('array' !== $type['name'] && 'ArrayCollection' !== $type['name']) {
return null;
}
// array<string, MyNamespaceMyObject>
if (isset($type['params'][1]['name'])) {
return [$type['params'][1], true];
}
// array<MyNamespaceMyObject>
if (isset($type['params'][0]['name'])) {
return [$type['params'][0], false];
}
return null;
}
/**
* @param mixed[] $type
*/
private function propertyTypeUsesGroups(array $type): ?bool
{
if (\array_key_exists($type['name'], $this->propertyTypeUseGroupsCache)) {
return $this->propertyTypeUseGroupsCache[$type['name']];
}
try {
$metadata = $this->factory->getMetadataForClass($type['name']);
foreach ($metadata->propertyMetadata as $item) {
if (property_exists($item, 'groups') && $item->groups !== [GroupsExclusionStrategy::DEFAULT_GROUP]) {
$this->propertyTypeUseGroupsCache[$type['name']] = true;
return true;
}
}
$this->propertyTypeUseGroupsCache[$type['name']] = false;
return false;
} catch (\ReflectionException) {
$this->propertyTypeUseGroupsCache[$type['name']] = null;
return null;
}
}
}