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

api-platform / core / 15256141101

26 May 2025 02:16PM UTC coverage: 21.714% (-4.8%) from 26.526%
15256141101

push

github

web-flow
Merge 4.1

6 of 387 new or added lines in 28 files covered. (1.55%)

1891 existing lines in 117 files now uncovered.

11118 of 51201 relevant lines covered (21.71%)

29.33 hits per line

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

63.77
/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 ApiPlatform\Metadata\Util\TypeHelper;
26
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
27
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
28
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
29
use Symfony\Component\TypeInfo\Type\BuiltinType;
30
use Symfony\Component\TypeInfo\Type\CollectionType;
31
use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
32
use Symfony\Component\TypeInfo\Type\ObjectType;
33
use Symfony\Component\TypeInfo\TypeIdentifier;
34

35
/**
36
 * {@inheritdoc}
37
 *
38
 * @author Kévin Dunglas <dunglas@gmail.com>
39
 */
40
final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareInterface
41
{
42
    use ResourceMetadataTrait;
43
    use SchemaUriPrefixTrait;
44

45
    private ?SchemaFactoryInterface $schemaFactory = null;
46
    // Edge case where the related resource is not readable (for example: NotExposed) but we have groups to read the whole related object
47
    public const OPENAPI_DEFINITION_NAME = 'openapi_definition_name';
48

49
    public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ?NameConverterInterface $nameConverter = null, ?ResourceClassResolverInterface $resourceClassResolver = null, ?array $distinctFormats = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null)
50
    {
51
        if (!$definitionNameFactory) {
710✔
52
            $this->definitionNameFactory = new DefinitionNameFactory($distinctFormats);
×
53
        }
54

55
        $this->resourceMetadataFactory = $resourceMetadataFactory;
710✔
56
        $this->resourceClassResolver = $resourceClassResolver;
710✔
57
    }
58

59
    /**
60
     * {@inheritdoc}
61
     */
62
    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
63
    {
64
        $schema = $schema ? clone $schema : new Schema();
15✔
65

66
        if (!$this->isResourceClass($className)) {
15✔
67
            $operation = null;
15✔
68
            $inputOrOutputClass = $className;
15✔
69
            $serializerContext ??= [];
15✔
70
        } else {
71
            $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
15✔
72
            $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
15✔
73
            $serializerContext ??= $this->getSerializerContext($operation, $type);
15✔
74
        }
75

76
        if (null === $inputOrOutputClass) {
15✔
77
            // input or output disabled
78
            return $schema;
15✔
79
        }
80

81
        $validationGroups = $operation ? $this->getValidationGroups($operation) : [];
15✔
82
        $version = $schema->getVersion();
15✔
83
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
15✔
84
        $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
15✔
85
        if (!$operation) {
15✔
86
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
15✔
87
        }
88

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

94
        if (!isset($schema['$ref']) && !isset($schema['type'])) {
15✔
95
            $ref = $this->getSchemaUriPrefix($version).$definitionName;
15✔
96
            if ($forceCollection || ('POST' !== $method && $operation instanceof CollectionOperationInterface)) {
15✔
97
                $schema['type'] = 'array';
15✔
98
                $schema['items'] = ['$ref' => $ref];
15✔
99
            } else {
100
                $schema['$ref'] = $ref;
15✔
101
            }
102
        }
103

104
        $definitions = $schema->getDefinitions();
15✔
105
        if (isset($definitions[$definitionName])) {
15✔
106
            // Already computed
107
            return $schema;
15✔
108
        }
109

110
        /** @var \ArrayObject<string, mixed> $definition */
111
        $definition = new \ArrayObject(['type' => 'object']);
15✔
112
        $definitions[$definitionName] = $definition;
15✔
113
        if ($description = $operation?->getDescription()) {
15✔
114
            $definition['description'] = $description;
15✔
115
        }
116

117
        // additionalProperties are allowed by default, so it does not need to be set explicitly, unless allow_extra_attributes is false
118
        // See https://json-schema.org/understanding-json-schema/reference/object.html#properties
119
        if (false === ($serializerContext[AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES] ?? true)) {
15✔
120
            $definition['additionalProperties'] = false;
×
121
        }
122

123
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
124
        if (Schema::VERSION_SWAGGER !== $version && $operation && $operation->getDeprecationReason()) {
15✔
125
            $definition['deprecated'] = true;
15✔
126
        }
127

128
        // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
129
        // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
130
        if ($operation instanceof HttpOperation && ($operation->getTypes()[0] ?? null)) {
15✔
131
            $definition['externalDocs'] = ['url' => $operation->getTypes()[0]];
15✔
132
        }
133

134
        $options = ['schema_type' => $type] + $this->getFactoryOptions($serializerContext, $validationGroups, $operation instanceof HttpOperation ? $operation : null);
15✔
135
        foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) {
15✔
136
            $propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName, $options);
15✔
137

138
            if (false === $propertyMetadata->isReadable() && false === $propertyMetadata->isWritable()) {
15✔
139
                continue;
15✔
140
            }
141

142
            $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $inputOrOutputClass, $format, $serializerContext) : $propertyName;
15✔
143
            if ($propertyMetadata->isRequired()) {
15✔
144
                $definition['required'][] = $normalizedPropertyName;
15✔
145
            }
146

147
            if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
15✔
148
                $this->buildLegacyPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type);
×
149
            } else {
150
                $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type);
15✔
151
            }
152
        }
153

154
        return $schema;
15✔
155
    }
156

157
    /**
158
     * Builds the JSON Schema for a property using the legacy PropertyInfo component.
159
     */
160
    private function buildLegacyPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void
161
    {
162
        $version = $schema->getVersion();
×
163
        if (Schema::VERSION_SWAGGER === $version || Schema::VERSION_OPENAPI === $version) {
×
164
            $additionalPropertySchema = $propertyMetadata->getOpenapiContext();
×
165
        } else {
166
            $additionalPropertySchema = $propertyMetadata->getJsonSchemaContext();
×
167
        }
168

169
        $propertySchema = array_merge(
×
170
            $propertyMetadata->getSchema() ?? [],
×
171
            $additionalPropertySchema ?? []
×
172
        );
×
173

174
        // @see https://github.com/api-platform/core/issues/6299
175
        if (Schema::UNKNOWN_TYPE === ($propertySchema['type'] ?? null) && isset($propertySchema['$ref'])) {
×
176
            unset($propertySchema['type']);
×
177
        }
178

179
        $extraProperties = $propertyMetadata->getExtraProperties() ?? [];
×
180
        // see AttributePropertyMetadataFactory
181
        if (true === ($extraProperties[SchemaPropertyMetadataFactory::JSON_SCHEMA_USER_DEFINED] ?? false)) {
×
182
            // schema seems to have been declared by the user: do not override nor complete user value
183
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
×
184

185
            return;
×
186
        }
187

188
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
189

190
        // never override the following keys if at least one is already set
191
        // or if property has no type(s) defined
192
        // or if property schema is already fully defined (type=string + format || enum)
193
        $propertySchemaType = $propertySchema['type'] ?? false;
×
194

195
        $isUnknown = Schema::UNKNOWN_TYPE === $propertySchemaType
×
196
            || ('array' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['items']['type'] ?? null))
×
197
            || ('object' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['additionalProperties']['type'] ?? null));
×
198

199
        // Scalar properties
200
        if (
201
            !$isUnknown && (
×
202
                [] === $types
×
203
                || ($propertySchema['$ref'] ?? $propertySchema['anyOf'] ?? $propertySchema['allOf'] ?? $propertySchema['oneOf'] ?? false)
×
204
                || (\is_array($propertySchemaType) ? \array_key_exists('string', $propertySchemaType) : 'string' !== $propertySchemaType)
×
205
                || ($propertySchema['format'] ?? $propertySchema['enum'] ?? false)
×
206
            )
207
        ) {
208
            if (isset($propertySchema['$ref'])) {
×
209
                unset($propertySchema['type']);
×
210
            }
211

212
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
×
213

214
            return;
×
215
        }
216

217
        // property schema is created in SchemaPropertyMetadataFactory, but it cannot build resource reference ($ref)
218
        // complete property schema with resource reference ($ref) only if it's related to an object
219
        $version = $schema->getVersion();
×
220
        $refs = [];
×
221
        $isNullable = null;
×
222

223
        foreach ($types as $type) {
×
224
            $subSchema = new Schema($version);
×
225
            $subSchema->setDefinitions($schema->getDefinitions()); // Populate definitions of the main schema
×
226

227
            $isCollection = $type->isCollection();
×
228
            if ($isCollection) {
×
229
                $valueType = $type->getCollectionValueTypes()[0] ?? null;
×
230
            } else {
231
                $valueType = $type;
×
232
            }
233

234
            $className = $valueType?->getClassName();
×
235
            if (null === $className) {
×
236
                continue;
×
237
            }
238

239
            $subSchemaFactory = $this->schemaFactory ?: $this;
×
240
            $subSchema = $subSchemaFactory->buildSchema($className, $format, $parentType, null, $subSchema, $serializerContext + [self::FORCE_SUBSCHEMA => true], false);
×
241
            if (!isset($subSchema['$ref'])) {
×
242
                continue;
×
243
            }
244

245
            if (false === $propertyMetadata->getGenId()) {
×
246
                $subDefinitionName = $this->definitionNameFactory->create($className, $format, $className, null, $serializerContext);
×
247

248
                if (isset($subSchema->getDefinitions()[$subDefinitionName])) {
×
249
                    unset($subSchema->getDefinitions()[$subDefinitionName]['properties']['@id']);
×
250
                }
251
            }
252

253
            if ($isCollection) {
×
254
                $key = ($propertySchema['type'] ?? null) === 'object' ? 'additionalProperties' : 'items';
×
255
                $propertySchema[$key]['$ref'] = $subSchema['$ref'];
×
256
                unset($propertySchema[$key]['type']);
×
257
                break;
×
258
            }
259

260
            $refs[] = ['$ref' => $subSchema['$ref']];
×
261
            $isNullable = $isNullable ?? $type->isNullable();
×
262
        }
263

264
        if ($isNullable) {
×
265
            $refs[] = ['type' => 'null'];
×
266
        }
267

268
        $c = \count($refs);
×
269
        if ($c > 1) {
×
270
            $propertySchema['anyOf'] = $refs;
×
271
            unset($propertySchema['type']);
×
272
        } elseif (1 === $c) {
×
273
            $propertySchema['$ref'] = $refs[0]['$ref'];
×
274
            unset($propertySchema['type']);
×
275
        }
276

277
        $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
×
278
    }
279

280
    private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void
281
    {
282
        $version = $schema->getVersion();
15✔
283
        if (Schema::VERSION_SWAGGER === $version || Schema::VERSION_OPENAPI === $version) {
15✔
284
            $additionalPropertySchema = $propertyMetadata->getOpenapiContext();
15✔
285
        } else {
UNCOV
286
            $additionalPropertySchema = $propertyMetadata->getJsonSchemaContext();
×
287
        }
288

289
        $propertySchema = array_merge(
15✔
290
            $propertyMetadata->getSchema() ?? [],
15✔
291
            $additionalPropertySchema ?? []
15✔
292
        );
15✔
293

294
        $extraProperties = $propertyMetadata->getExtraProperties() ?? [];
15✔
295
        // see AttributePropertyMetadataFactory
296
        if (true === ($extraProperties[SchemaPropertyMetadataFactory::JSON_SCHEMA_USER_DEFINED] ?? false)) {
15✔
297
            // schema seems to have been declared by the user: do not override nor complete user value
298
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
15✔
299

300
            return;
15✔
301
        }
302

303
        $type = $propertyMetadata->getNativeType();
15✔
304

305
        // Type is defined in an allOf, anyOf, or oneOf
306
        $propertySchemaType = $this->getSchemaValue($propertySchema, 'type');
15✔
307
        $currentRef = $this->getSchemaValue($propertySchema, '$ref');
15✔
308
        $isSchemaDefined = null !== ($currentRef ?? $this->getSchemaValue($propertySchema, 'format') ?? $this->getSchemaValue($propertySchema, 'enum'));
15✔
309
        if (!$isSchemaDefined && Schema::UNKNOWN_TYPE !== $propertySchemaType) {
15✔
310
            $isSchemaDefined = true;
15✔
311
        }
312

313
        // Check if the type is considered "unknown" by SchemaPropertyMetadataFactory
314
        if (isset($propertySchema['additionalProperties']['type']) && Schema::UNKNOWN_TYPE === $propertySchema['additionalProperties']['type']) {
15✔
315
            $isSchemaDefined = false;
15✔
316
        }
317

318
        if ($isSchemaDefined && Schema::UNKNOWN_TYPE !== $propertySchemaType) {
15✔
319
            // If schema is defined and not marked as unknown, or if no type info exists, return early
320
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
15✔
321

322
            return;
15✔
323
        }
324

325
        if (Schema::UNKNOWN_TYPE === $propertySchemaType) {
15✔
326
            $propertySchema = [];
15✔
327
        }
328

329
        // property schema is created in SchemaPropertyMetadataFactory, but it cannot build resource reference ($ref)
330
        // complete property schema with resource reference ($ref) if it's related to an object/resource
331
        $refs = [];
15✔
332
        $isNullable = $type?->isNullable() ?? false;
15✔
333

334
        // TODO: refactor this with TypeInfo we shouldn't have to loop like this, the below code handles object refs
335
        if ($type) {
15✔
336
            foreach ($type instanceof CompositeTypeInterface ? $type->getTypes() : [$type] as $t) {
15✔
337
                if ($t instanceof BuiltinType && TypeIdentifier::NULL === $t->getTypeIdentifier()) {
15✔
338
                    continue;
15✔
339
                }
340

341
                $valueType = $t;
15✔
342
                $isCollection = $t instanceof CollectionType;
15✔
343

344
                if ($isCollection) {
15✔
345
                    $valueType = TypeHelper::getCollectionValueType($t);
15✔
346
                }
347

348
                if (!$valueType instanceof ObjectType) {
15✔
349
                    continue;
×
350
                }
351

352
                $className = $valueType->getClassName();
15✔
353
                $subSchemaInstance = new Schema($version);
15✔
354
                $subSchemaInstance->setDefinitions($schema->getDefinitions());
15✔
355
                $subSchemaFactory = $this->schemaFactory ?: $this;
15✔
356
                $subSchemaResult = $subSchemaFactory->buildSchema($className, $format, $parentType, null, $subSchemaInstance, $serializerContext + [self::FORCE_SUBSCHEMA => true], false);
15✔
357
                if (!isset($subSchemaResult['$ref'])) {
15✔
358
                    continue;
×
359
                }
360

361
                if (false === $propertyMetadata->getGenId()) {
15✔
362
                    $subDefinitionName = $this->definitionNameFactory->create($className, $format, $className, null, $serializerContext);
15✔
363
                    if (isset($subSchemaResult->getDefinitions()[$subDefinitionName]['properties']['@id'])) {
15✔
364
                        unset($subSchemaResult->getDefinitions()[$subDefinitionName]['properties']['@id']);
×
365
                    }
366
                }
367

368
                if ($isCollection) {
15✔
369
                    $key = ($propertySchema['type'] ?? null) === 'object' ? 'additionalProperties' : 'items';
15✔
370
                    if (!isset($propertySchema['type'])) {
15✔
371
                        $propertySchema['type'] = 'array';
15✔
372
                    }
373

374
                    if (!isset($propertySchema[$key]) || !\is_array($propertySchema[$key])) {
15✔
375
                        $propertySchema[$key] = [];
15✔
376
                    }
377
                    $propertySchema[$key] = ['$ref' => $subSchemaResult['$ref']];
15✔
378
                    $refs = [];
15✔
379
                    break;
15✔
380
                }
381

382
                $refs[] = ['$ref' => $subSchemaResult['$ref']];
15✔
383
            }
384
        }
385

386
        if (!empty($refs)) {
15✔
387
            if ($isNullable) {
15✔
388
                $refs[] = ['type' => 'null'];
15✔
389
            }
390

391
            if (($c = \count($refs)) > 1) {
15✔
392
                $propertySchema = ['anyOf' => $refs];
15✔
393
            } elseif (1 === $c) {
15✔
394
                $propertySchema = ['$ref' => $refs[0]['$ref']];
15✔
395
            }
396
        }
397

398
        if (null !== $propertyMetadata->getUriTemplate() || (!\array_key_exists('readOnly', $propertySchema) && false === $propertyMetadata->isWritable() && !$propertyMetadata->isInitializable()) && !isset($propertySchema['$ref'])) {
15✔
399
            $propertySchema['readOnly'] = true;
15✔
400
        }
401

402
        $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
15✔
403
    }
404

405
    private function getValidationGroups(Operation $operation): array
406
    {
407
        $groups = $operation->getValidationContext()['groups'] ?? [];
15✔
408

409
        return \is_array($groups) ? $groups : [$groups];
15✔
410
    }
411

412
    /**
413
     * Gets the options for the property name collection / property metadata factories.
414
     */
415
    private function getFactoryOptions(array $serializerContext, array $validationGroups, ?HttpOperation $operation = null): array
416
    {
417
        $options = [
15✔
418
            /* @see https://github.com/symfony/symfony/blob/v5.1.0/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php */
419
            'enable_getter_setter_extraction' => true,
15✔
420
        ];
15✔
421

422
        if (isset($serializerContext[AbstractNormalizer::GROUPS])) {
15✔
423
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
424
            $options['serializer_groups'] = (array) $serializerContext[AbstractNormalizer::GROUPS];
15✔
425
        }
426

427
        if ($operation && ($normalizationGroups = $operation->getNormalizationContext()['groups'] ?? null)) {
15✔
428
            $options['normalization_groups'] = $normalizationGroups;
15✔
429
        }
430

431
        if ($operation && ($denormalizationGroups = $operation->getDenormalizationContext()['groups'] ?? null)) {
15✔
432
            $options['denormalization_groups'] = $denormalizationGroups;
15✔
433
        }
434

435
        if ($validationGroups) {
15✔
436
            $options['validation_groups'] = $validationGroups;
×
437
        }
438

439
        if ($operation && ($ignoredAttributes = $operation->getNormalizationContext()['ignored_attributes'] ?? null)) {
15✔
440
            $options['ignored_attributes'] = $ignoredAttributes;
15✔
441
        }
442

443
        return $options;
15✔
444
    }
445

446
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
447
    {
448
        $this->schemaFactory = $schemaFactory;
710✔
449
    }
450

451
    private function getSchemaValue(array $schema, string $key): array|string|null
452
    {
453
        if (isset($schema['items'])) {
15✔
454
            $schema = $schema['items'];
15✔
455
        }
456

457
        return $schema[$key] ?? $schema['allOf'][0][$key] ?? $schema['anyOf'][0][$key] ?? $schema['oneOf'][0][$key] ?? null;
15✔
458
    }
459
}
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