-
-
Notifications
You must be signed in to change notification settings - Fork 899
Expand file tree
/
Copy pathObjectModelDescriber.php
More file actions
261 lines (218 loc) · 10.1 KB
/
ObjectModelDescriber.php
File metadata and controls
261 lines (218 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
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
<?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 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\PropertyDescriber\PropertyDescriberInterface;
use Nelmio\ApiDocBundle\TypeDescriber\TypeDescriberInterface;
use OpenApi\Annotations as OA;
use OpenApi\Generator;
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\PropertyInfo\Type as LegacyType;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\ObjectType;
class ObjectModelDescriber implements ModelDescriberInterface, ModelRegistryAwareInterface
{
use ApplyOpenApiDiscriminatorTrait;
use ModelRegistryAwareTrait;
private PropertyInfoExtractorInterface $propertyInfo;
private ?ClassMetadataFactoryInterface $classMetadataFactory;
private PropertyDescriberInterface|TypeDescriberInterface $propertyDescriber;
/** @var string[] */
private array $mediaTypes;
/** @var (NameConverterInterface&AdvancedNameConverterInterface)|null */
private ?NameConverterInterface $nameConverter;
private bool $useValidationGroups;
/**
* @param (NameConverterInterface&AdvancedNameConverterInterface)|null $nameConverter
* @param string[] $mediaTypes
*/
public function __construct(
PropertyInfoExtractorInterface $propertyInfo,
PropertyDescriberInterface|TypeDescriberInterface $propertyDescribers,
array $mediaTypes,
?NameConverterInterface $nameConverter = null,
bool $useValidationGroups = false,
?ClassMetadataFactoryInterface $classMetadataFactory = null,
) {
$this->propertyInfo = $propertyInfo;
$this->propertyDescriber = $propertyDescribers;
$this->mediaTypes = $mediaTypes;
$this->nameConverter = $nameConverter;
$this->useValidationGroups = $useValidationGroups;
$this->classMetadataFactory = $classMetadataFactory;
}
public function describe(Model $model, OA\Schema $schema): void
{
$type = $model->getTypeInfo();
if (!$type instanceof ObjectType) {
return;
}
$class = $type->getClassName();
$schema->_context->class = $class;
$context = ['serializer_groups' => null];
if (null !== $model->getGroups()) {
$context['serializer_groups'] = array_filter($model->getGroups(), 'is_string');
}
$reflClass = new \ReflectionClass($class);
$annotationsReader = new AnnotationsReader(
$this->modelRegistry,
$this->mediaTypes,
$this->useValidationGroups
);
$classResult = $annotationsReader->updateDefinition($reflClass, $schema);
if (!$classResult) {
return;
}
$schema->type = 'object';
$mapping = false;
$attributesMetadata = [];
if (null !== $this->classMetadataFactory) {
$classMetadata = $this->classMetadataFactory->getMetadataFor($class);
$mapping = $classMetadata->getClassDiscriminatorMapping();
$attributesMetadata = $classMetadata->getAttributesMetadata();
}
if ($mapping && Generator::UNDEFINED === $schema->discriminator) {
$this->applyOpenApiDiscriminator(
$model,
$schema,
$this->modelRegistry,
$mapping->getTypeProperty(),
$mapping->getTypesMapping()
);
}
$propertyInfoProperties = $this->propertyInfo->getProperties($class, $context);
if (null === $propertyInfoProperties) {
return;
}
// Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/1756
// The SerializerExtractor does expose private/protected properties for some reason, so we eliminate them here
$propertyInfoProperties = array_intersect($propertyInfoProperties, $this->propertyInfo->getProperties($class, []) ?? []);
foreach ($propertyInfoProperties as $propertyName) {
$serializedName = null !== $this->nameConverter ? $this->nameConverter->normalize($propertyName, $class, null, $model->getSerializationContext()) : $propertyName;
$reflections = $this->getReflections($reflClass, $propertyName);
if (!$annotationsReader->shouldDescribeProperty($reflections)) {
continue;
}
// Check if a custom name is set
foreach ($reflections as $reflection) {
$serializedName = $annotationsReader->getPropertyName($reflection, $serializedName);
}
$property = Util::getProperty($schema, $serializedName);
// Interpret additional options
$groups = $model->getGroups();
if (isset($groups[$propertyName]) && \is_array($groups[$propertyName])) {
$groups = $model->getGroups()[$propertyName];
}
foreach ($reflections as $reflection) {
$annotationsReader->updateProperty($reflection, $property, $groups);
}
// If type manually defined
if (Generator::UNDEFINED !== $property->type || Generator::UNDEFINED !== $property->ref) {
continue;
}
if ($this->propertyDescriber instanceof TypeDescriberInterface) {
$types = $this->propertyInfo->getType($class, $propertyName);
} else {
$types = $this->propertyInfo->getTypes($class, $propertyName);
}
if (null === $types) {
throw new \LogicException(\sprintf('The PropertyInfo component was not able to guess the type of %s::$%s. You may need to add a `@var` annotation or use `#[OA\Property(type="")]` to make its type explicit.', $class, $propertyName));
}
$propertyContext = $model->getSerializationContext();
if (isset($attributesMetadata[$propertyName])) {
$propertyContext = array_merge(
$propertyContext,
$attributesMetadata[$propertyName]->getNormalizationContextForGroups(
array_filter($groups ?? [], 'is_string')
)
);
}
$this->describeProperty($types, $model, $property, $propertyName, $propertyContext);
}
$this->markRequiredProperties($schema);
}
/**
* @return \ReflectionProperty[]|\ReflectionMethod[]
*/
private function getReflections(\ReflectionClass $reflClass, string $propertyName): array
{
$reflections = [];
if ($reflClass->hasProperty($propertyName)) {
$reflections[] = $reflClass->getProperty($propertyName);
}
$camelProp = $this->camelize($propertyName);
foreach (['', 'get', 'is', 'has', 'can', 'add', 'remove', 'set'] as $prefix) {
if ($reflClass->hasMethod($prefix.$camelProp)) {
$reflections[] = $reflClass->getMethod($prefix.$camelProp);
}
}
return $reflections;
}
/**
* Camelizes a given string.
*/
private function camelize(string $string): string
{
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}
/**
* @param LegacyType[]|Type $types
* @param array<string, mixed> $propertyContext
*/
private function describeProperty(array|Type $types, Model $model, OA\Schema $property, string $propertyName, array $propertyContext = []): void
{
$context = [] !== $propertyContext ? $propertyContext : $model->getSerializationContext();
if ($this->propertyDescriber instanceof ModelRegistryAwareInterface) {
$this->propertyDescriber->setModelRegistry($this->modelRegistry);
}
if ($this->propertyDescriber->supports($types, $context)) {
$this->propertyDescriber->describe($types, $property, $context);
return;
}
throw new \Exception(\sprintf('Type "%s" is not supported in %s::$%s. You may need to use the `#[OA\Property(type="")]` attribute to specify it manually.', \is_array($types) ? $types[0]->getBuiltinType() : $types, $model->getTypeInfo(), $propertyName));
}
/**
* Mark properties as required while ordering them in the same order as the properties of the schema.
* Then append the original required properties.
*/
private function markRequiredProperties(OA\Schema $schema): void
{
if (Generator::isDefault($properties = $schema->properties)) {
return;
}
$newRequired = [];
foreach ($properties as $property) {
if (\is_array($schema->required) && \in_array($property->property, $schema->required, true)) {
$newRequired[] = $property->property;
continue;
}
if (true === $property->nullable || !Generator::isDefault($property->default)) {
continue;
}
$newRequired[] = $property->property;
}
if ([] !== $newRequired) {
$originalRequired = Generator::isDefault($schema->required) ? [] : $schema->required;
$schema->required = array_values(array_unique(array_merge($newRequired, $originalRequired)));
}
}
public function supports(Model $model): bool
{
return $model->getTypeInfo() instanceof ObjectType
&& (class_exists($model->getTypeInfo()->getClassName()) || interface_exists($model->getTypeInfo()->getClassName()));
}
}