• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 15133993414

20 May 2025 09:30AM UTC coverage: 26.313% (-1.2%) from 27.493%
15133993414

Pull #7161

github

web-flow
Merge e2c03d45f into 5459ba375
Pull Request #7161: fix(metadata): infer parameter string type from schema

0 of 2 new or added lines in 1 file covered. (0.0%)

11019 existing lines in 363 files now uncovered.

12898 of 49018 relevant lines covered (26.31%)

34.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.95
/src/JsonSchema/SchemaFactory.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace ApiPlatform\JsonSchema;
15

16
use ApiPlatform\JsonSchema\Metadata\Property\Factory\SchemaPropertyMetadataFactory;
17
use ApiPlatform\Metadata\ApiProperty;
18
use ApiPlatform\Metadata\CollectionOperationInterface;
19
use ApiPlatform\Metadata\HttpOperation;
20
use ApiPlatform\Metadata\Operation;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
26
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
27

28
/**
29
 * {@inheritdoc}
30
 *
31
 * @author Kévin Dunglas <dunglas@gmail.com>
32
 */
33
final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareInterface
34
{
35
    use ResourceMetadataTrait;
36

37
    private ?SchemaFactoryInterface $schemaFactory = null;
38
    // Edge case where the related resource is not readable (for example: NotExposed) but we have groups to read the whole related object
39
    public const FORCE_SUBSCHEMA = '_api_subschema_force_readable_link';
40
    public const OPENAPI_DEFINITION_NAME = 'openapi_definition_name';
41

42
    public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ?NameConverterInterface $nameConverter = null, ?ResourceClassResolverInterface $resourceClassResolver = null, private readonly ?array $distinctFormats = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null)
43
    {
UNCOV
44
        if (!$definitionNameFactory) {
828✔
45
            $this->definitionNameFactory = new DefinitionNameFactory($this->distinctFormats);
×
46
        }
47

UNCOV
48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
828✔
UNCOV
49
        $this->resourceClassResolver = $resourceClassResolver;
828✔
50
    }
51

52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema
56
    {
UNCOV
57
        $schema = $schema ? clone $schema : new Schema();
65✔
58

UNCOV
59
        if (!$this->isResourceClass($className)) {
65✔
UNCOV
60
            $operation = null;
37✔
UNCOV
61
            $inputOrOutputClass = $className;
37✔
UNCOV
62
            $serializerContext ??= [];
37✔
63
        } else {
UNCOV
64
            $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
61✔
UNCOV
65
            $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
61✔
UNCOV
66
            $serializerContext ??= $this->getSerializerContext($operation, $type);
61✔
67
        }
68

UNCOV
69
        if (null === $inputOrOutputClass) {
65✔
70
            // input or output disabled
71
            return $schema;
12✔
72
        }
73

UNCOV
74
        $validationGroups = $operation ? $this->getValidationGroups($operation) : [];
65✔
UNCOV
75
        $version = $schema->getVersion();
65✔
UNCOV
76
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
65✔
UNCOV
77
        $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
65✔
UNCOV
78
        if (!$operation) {
65✔
UNCOV
79
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
37✔
80
        }
81

82
        // In case of FORCE_SUBSCHEMA an object can be writable through another class even though it has no POST operation
UNCOV
83
        if (!($serializerContext[self::FORCE_SUBSCHEMA] ?? false) && Schema::TYPE_OUTPUT !== $type && !\in_array($method, ['POST', 'PATCH', 'PUT'], true)) {
65✔
84
            return $schema;
×
85
        }
86

UNCOV
87
        if (!isset($schema['$ref']) && !isset($schema['type'])) {
65✔
UNCOV
88
            $ref = Schema::VERSION_OPENAPI === $version ? '#/components/schemas/'.$definitionName : '#/definitions/'.$definitionName;
65✔
UNCOV
89
            if ($forceCollection || ('POST' !== $method && $operation instanceof CollectionOperationInterface)) {
65✔
UNCOV
90
                $schema['type'] = 'array';
36✔
UNCOV
91
                $schema['items'] = ['$ref' => $ref];
36✔
92
            } else {
UNCOV
93
                $schema['$ref'] = $ref;
59✔
94
            }
95
        }
96

UNCOV
97
        $definitions = $schema->getDefinitions();
65✔
UNCOV
98
        if (isset($definitions[$definitionName])) {
65✔
99
            // Already computed
UNCOV
100
            return $schema;
28✔
101
        }
102

103
        /** @var \ArrayObject<string, mixed> $definition */
UNCOV
104
        $definition = new \ArrayObject(['type' => 'object']);
65✔
UNCOV
105
        $definitions[$definitionName] = $definition;
65✔
UNCOV
106
        $definition['description'] = $operation ? ($operation->getDescription() ?? '') : '';
65✔
107

108
        // additionalProperties are allowed by default, so it does not need to be set explicitly, unless allow_extra_attributes is false
109
        // See https://json-schema.org/understanding-json-schema/reference/object.html#properties
UNCOV
110
        if (false === ($serializerContext[AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES] ?? true)) {
65✔
111
            $definition['additionalProperties'] = false;
×
112
        }
113

114
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
UNCOV
115
        if (Schema::VERSION_SWAGGER !== $version && $operation && $operation->getDeprecationReason()) {
65✔
116
            $definition['deprecated'] = true;
12✔
117
        } else {
UNCOV
118
            $definition['deprecated'] = false;
65✔
119
        }
120

121
        // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
122
        // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
UNCOV
123
        if ($operation instanceof HttpOperation && ($operation->getTypes()[0] ?? null)) {
65✔
UNCOV
124
            $definition['externalDocs'] = ['url' => $operation->getTypes()[0]];
16✔
125
        }
126

UNCOV
127
        $options = ['schema_type' => $type] + $this->getFactoryOptions($serializerContext, $validationGroups, $operation instanceof HttpOperation ? $operation : null);
65✔
UNCOV
128
        foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) {
65✔
UNCOV
129
            $propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName, $options);
61✔
UNCOV
130
            if (!$propertyMetadata->isReadable() && !$propertyMetadata->isWritable()) {
61✔
UNCOV
131
                continue;
25✔
132
            }
133

UNCOV
134
            $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $inputOrOutputClass, $format, $serializerContext) : $propertyName;
61✔
UNCOV
135
            if ($propertyMetadata->isRequired()) {
61✔
UNCOV
136
                $definition['required'][] = $normalizedPropertyName;
24✔
137
            }
138

UNCOV
139
            $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type);
61✔
140
        }
141

UNCOV
142
        return $schema;
65✔
143
    }
144

145
    private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void
146
    {
UNCOV
147
        $version = $schema->getVersion();
61✔
UNCOV
148
        if (Schema::VERSION_SWAGGER === $version || Schema::VERSION_OPENAPI === $version) {
61✔
UNCOV
149
            $additionalPropertySchema = $propertyMetadata->getOpenapiContext();
22✔
150
        } else {
UNCOV
151
            $additionalPropertySchema = $propertyMetadata->getJsonSchemaContext();
39✔
152
        }
153

UNCOV
154
        $propertySchema = array_merge(
61✔
UNCOV
155
            $propertyMetadata->getSchema() ?? [],
61✔
UNCOV
156
            $additionalPropertySchema ?? []
61✔
UNCOV
157
        );
61✔
158

159
        // @see https://github.com/api-platform/core/issues/6299
UNCOV
160
        if (Schema::UNKNOWN_TYPE === ($propertySchema['type'] ?? null) && isset($propertySchema['$ref'])) {
61✔
UNCOV
161
            unset($propertySchema['type']);
13✔
162
        }
163

UNCOV
164
        $extraProperties = $propertyMetadata->getExtraProperties() ?? [];
61✔
165
        // see AttributePropertyMetadataFactory
UNCOV
166
        if (true === ($extraProperties[SchemaPropertyMetadataFactory::JSON_SCHEMA_USER_DEFINED] ?? false)) {
61✔
167
            // schema seems to have been declared by the user: do not override nor complete user value
UNCOV
168
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
22✔
169

UNCOV
170
            return;
22✔
171
        }
172

UNCOV
173
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
61✔
174

175
        // never override the following keys if at least one is already set
176
        // or if property has no type(s) defined
177
        // or if property schema is already fully defined (type=string + format || enum)
UNCOV
178
        $propertySchemaType = $propertySchema['type'] ?? false;
61✔
179

UNCOV
180
        $isUnknown = Schema::UNKNOWN_TYPE === $propertySchemaType
61✔
UNCOV
181
            || ('array' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['items']['type'] ?? null))
61✔
UNCOV
182
            || ('object' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['additionalProperties']['type'] ?? null));
61✔
183

184
        if (
UNCOV
185
            !$isUnknown && (
61✔
UNCOV
186
                [] === $types
61✔
UNCOV
187
                || ($propertySchema['$ref'] ?? $propertySchema['anyOf'] ?? $propertySchema['allOf'] ?? $propertySchema['oneOf'] ?? false)
61✔
UNCOV
188
                || (\is_array($propertySchemaType) ? \array_key_exists('string', $propertySchemaType) : 'string' !== $propertySchemaType)
61✔
UNCOV
189
                || ($propertySchema['format'] ?? $propertySchema['enum'] ?? false)
61✔
190
            )
191
        ) {
UNCOV
192
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
48✔
193

UNCOV
194
            return;
48✔
195
        }
196

197
        // property schema is created in SchemaPropertyMetadataFactory, but it cannot build resource reference ($ref)
198
        // complete property schema with resource reference ($ref) only if it's related to an object
UNCOV
199
        $version = $schema->getVersion();
54✔
UNCOV
200
        $refs = [];
54✔
UNCOV
201
        $isNullable = null;
54✔
202

UNCOV
203
        foreach ($types as $type) {
54✔
UNCOV
204
            $subSchema = new Schema($version);
54✔
UNCOV
205
            $subSchema->setDefinitions($schema->getDefinitions()); // Populate definitions of the main schema
54✔
206

UNCOV
207
            $isCollection = $type->isCollection();
54✔
UNCOV
208
            if ($isCollection) {
54✔
UNCOV
209
                $valueType = $type->getCollectionValueTypes()[0] ?? null;
32✔
210
            } else {
UNCOV
211
                $valueType = $type;
54✔
212
            }
213

UNCOV
214
            $className = $valueType?->getClassName();
54✔
UNCOV
215
            if (null === $className) {
54✔
UNCOV
216
                continue;
54✔
217
            }
218

UNCOV
219
            $subSchemaFactory = $this->schemaFactory ?: $this;
39✔
UNCOV
220
            $subSchema = $subSchemaFactory->buildSchema($className, $format, $parentType, null, $subSchema, $serializerContext + [self::FORCE_SUBSCHEMA => true], false);
39✔
UNCOV
221
            if (!isset($subSchema['$ref'])) {
39✔
222
                continue;
12✔
223
            }
224

UNCOV
225
            if (false === $propertyMetadata->getGenId()) {
39✔
UNCOV
226
                $subDefinitionName = $this->definitionNameFactory->create($className, $format, $className, null, $serializerContext);
13✔
227

UNCOV
228
                if (isset($subSchema->getDefinitions()[$subDefinitionName])) {
13✔
UNCOV
229
                    unset($subSchema->getDefinitions()[$subDefinitionName]['properties']['@id']);
13✔
230
                }
231
            }
232

UNCOV
233
            if ($isCollection) {
39✔
UNCOV
234
                $key = ($propertySchema['type'] ?? null) === 'object' ? 'additionalProperties' : 'items';
27✔
UNCOV
235
                $propertySchema[$key]['$ref'] = $subSchema['$ref'];
27✔
UNCOV
236
                unset($propertySchema[$key]['type']);
27✔
UNCOV
237
                break;
27✔
238
            }
239

UNCOV
240
            $refs[] = ['$ref' => $subSchema['$ref']];
31✔
UNCOV
241
            $isNullable = $isNullable ?? $type->isNullable();
31✔
242
        }
243

UNCOV
244
        if ($isNullable) {
54✔
UNCOV
245
            $refs[] = ['type' => 'null'];
26✔
246
        }
247

UNCOV
248
        if (($c = \count($refs)) > 1) {
54✔
UNCOV
249
            $propertySchema['anyOf'] = $refs;
26✔
UNCOV
250
            unset($propertySchema['type']);
26✔
UNCOV
251
        } elseif (1 === $c) {
54✔
UNCOV
252
            $propertySchema['$ref'] = $refs[0]['$ref'];
23✔
UNCOV
253
            unset($propertySchema['type']);
23✔
254
        }
255

UNCOV
256
        $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
54✔
257
    }
258

259
    private function getValidationGroups(Operation $operation): array
260
    {
UNCOV
261
        $groups = $operation->getValidationContext()['groups'] ?? [];
61✔
262

UNCOV
263
        return \is_array($groups) ? $groups : [$groups];
61✔
264
    }
265

266
    /**
267
     * Gets the options for the property name collection / property metadata factories.
268
     */
269
    private function getFactoryOptions(array $serializerContext, array $validationGroups, ?HttpOperation $operation = null): array
270
    {
UNCOV
271
        $options = [
65✔
272
            /* @see https://github.com/symfony/symfony/blob/v5.1.0/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php */
UNCOV
273
            'enable_getter_setter_extraction' => true,
65✔
UNCOV
274
        ];
65✔
275

UNCOV
276
        if (isset($serializerContext[AbstractNormalizer::GROUPS])) {
65✔
277
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
UNCOV
278
            $options['serializer_groups'] = (array) $serializerContext[AbstractNormalizer::GROUPS];
28✔
279
        }
280

UNCOV
281
        if ($operation && ($normalizationGroups = $operation->getNormalizationContext()['groups'] ?? null)) {
65✔
UNCOV
282
            $options['normalization_groups'] = $normalizationGroups;
31✔
283
        }
284

UNCOV
285
        if ($operation && ($denormalizationGroups = $operation->getDenormalizationContext()['groups'] ?? null)) {
65✔
UNCOV
286
            $options['denormalization_groups'] = $denormalizationGroups;
16✔
287
        }
288

UNCOV
289
        if ($validationGroups) {
65✔
290
            $options['validation_groups'] = $validationGroups;
×
291
        }
292

UNCOV
293
        if ($operation && ($ignoredAttributes = $operation->getNormalizationContext()['ignored_attributes'] ?? null)) {
65✔
UNCOV
294
            $options['ignored_attributes'] = $ignoredAttributes;
26✔
295
        }
296

UNCOV
297
        return $options;
65✔
298
    }
299

300
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
301
    {
UNCOV
302
        $this->schemaFactory = $schemaFactory;
828✔
303
    }
304
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc