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

api-platform / core / 15040977736

15 May 2025 09:02AM UTC coverage: 21.754% (+13.3%) from 8.423%
15040977736

Pull #6960

github

web-flow
Merge 7a7a13526 into 1862d03b7
Pull Request #6960: feat(json-schema): mutualize json schema between formats

320 of 460 new or added lines in 24 files covered. (69.57%)

1863 existing lines in 109 files now uncovered.

11069 of 50882 relevant lines covered (21.75%)

29.49 hits per line

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

63.24
/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✔
NEW
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
        ) {
NEW
208
            if (isset($propertySchema['$ref'])) {
×
NEW
209
                unset($propertySchema['type']);
×
210
            }
211

UNCOV
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

NEW
268
        $c = \count($refs);
×
NEW
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
        // @see https://github.com/api-platform/core/issues/6299
295
        if (Schema::UNKNOWN_TYPE === ($propertySchema['type'] ?? null) && isset($propertySchema['$ref'])) {
15✔
UNCOV
296
            unset($propertySchema['type']);
×
297
        }
298

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

305
            return;
15✔
306
        }
307

308
        $type = $propertyMetadata->getNativeType();
15✔
309
        $propertySchemaType = $propertySchema['type'] ?? false;
15✔
310
        $isSchemaDefined = ($propertySchema['$ref'] ?? $propertySchema['anyOf'] ?? $propertySchema['allOf'] ?? $propertySchema['oneOf'] ?? false)
15✔
311
            || ($propertySchemaType && 'string' !== $propertySchemaType && !(\is_array($propertySchemaType) && !\in_array('string', $propertySchemaType, true)))
15✔
312
            || (($propertySchema['format'] ?? $propertySchema['enum'] ?? false) && $propertySchemaType);
15✔
313

314
        // Check if the type is considered "unknown" by SchemaPropertyMetadataFactory
315
        $isUnknown = Schema::UNKNOWN_TYPE === $propertySchemaType
15✔
316
            || ('array' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['items']['type'] ?? null))
15✔
317
            || ('object' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['additionalProperties']['type'] ?? null));
15✔
318

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

323
            return;
15✔
324
        }
325

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

332
        if ($type) {
15✔
333
            foreach ($type instanceof CompositeTypeInterface ? $type->getTypes() : [$type] as $t) {
15✔
334
                if ($t instanceof BuiltinType && TypeIdentifier::NULL === $t->getTypeIdentifier()) {
15✔
335
                    continue;
15✔
336
                }
337

338
                $valueType = $t;
15✔
339
                $isCollection = $t instanceof CollectionType;
15✔
340

341
                if ($isCollection) {
15✔
342
                    $valueType = TypeHelper::getCollectionValueType($t);
15✔
343
                }
344

345
                if (!$valueType instanceof ObjectType) {
15✔
346
                    continue;
15✔
347
                }
348

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

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

365
                if ($isCollection) {
15✔
366
                    $key = ($propertySchema['type'] ?? null) === 'object' ? 'additionalProperties' : 'items';
15✔
367
                    if (!isset($propertySchema[$key]) || !\is_array($propertySchema[$key])) {
15✔
368
                        $propertySchema[$key] = [];
15✔
369
                    }
370
                    $propertySchema[$key]['$ref'] = $subSchemaResult['$ref'];
15✔
371
                    unset($propertySchema[$key]['type']);
15✔
372
                    $refs = [];
15✔
373
                    break;
15✔
374
                }
375

376
                $refs[] = ['$ref' => $subSchemaResult['$ref']];
15✔
377
            }
378
        }
379

380
        if (!empty($refs)) {
15✔
381
            if ($isNullable) {
15✔
382
                $refs[] = ['type' => 'null'];
15✔
383
            }
384

385
            if (($c = \count($refs)) > 1) {
15✔
386
                $propertySchema['anyOf'] = $refs;
15✔
387
                unset($propertySchema['type'], $propertySchema['$ref']);
15✔
388
            } elseif (1 === $c) {
15✔
389
                $propertySchema['$ref'] = $refs[0]['$ref'];
15✔
390
                unset($propertySchema['type']);
15✔
391
            }
392
        }
393

394
        $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = new \ArrayObject($propertySchema);
15✔
395
    }
396

397
    private function getValidationGroups(Operation $operation): array
398
    {
399
        $groups = $operation->getValidationContext()['groups'] ?? [];
15✔
400

401
        return \is_array($groups) ? $groups : [$groups];
15✔
402
    }
403

404
    /**
405
     * Gets the options for the property name collection / property metadata factories.
406
     */
407
    private function getFactoryOptions(array $serializerContext, array $validationGroups, ?HttpOperation $operation = null): array
408
    {
409
        $options = [
15✔
410
            /* @see https://github.com/symfony/symfony/blob/v5.1.0/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php */
411
            'enable_getter_setter_extraction' => true,
15✔
412
        ];
15✔
413

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

419
        if ($operation && ($normalizationGroups = $operation->getNormalizationContext()['groups'] ?? null)) {
15✔
420
            $options['normalization_groups'] = $normalizationGroups;
15✔
421
        }
422

423
        if ($operation && ($denormalizationGroups = $operation->getDenormalizationContext()['groups'] ?? null)) {
15✔
424
            $options['denormalization_groups'] = $denormalizationGroups;
15✔
425
        }
426

427
        if ($validationGroups) {
15✔
428
            $options['validation_groups'] = $validationGroups;
×
429
        }
430

431
        if ($operation && ($ignoredAttributes = $operation->getNormalizationContext()['ignored_attributes'] ?? null)) {
15✔
432
            $options['ignored_attributes'] = $ignoredAttributes;
15✔
433
        }
434

435
        return $options;
15✔
436
    }
437

438
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
439
    {
440
        $this->schemaFactory = $schemaFactory;
710✔
441
    }
442
}
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