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

api-platform / core / 14008635868

22 Mar 2025 12:39PM UTC coverage: 8.52% (+0.005%) from 8.515%
14008635868

Pull #7042

github

web-flow
Merge fdd88ef56 into 47a6dffbb
Pull Request #7042: Purge parent collections in inheritance cases

4 of 9 new or added lines in 1 file covered. (44.44%)

540 existing lines in 57 files now uncovered.

13394 of 157210 relevant lines covered (8.52%)

22.93 hits per line

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

97.71
/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
    {
44
        if (!$definitionNameFactory) {
1,769✔
45
            $this->definitionNameFactory = new DefinitionNameFactory($this->distinctFormats);
×
46
        }
47

48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
1,769✔
49
        $this->resourceClassResolver = $resourceClassResolver;
1,769✔
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
    {
57
        $schema = $schema ? clone $schema : new Schema();
133✔
58

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

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

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

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

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

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

103
        /** @var \ArrayObject<string, mixed> $definition */
104
        $definition = new \ArrayObject(['type' => 'object']);
133✔
105
        $definitions[$definitionName] = $definition;
133✔
106
        $definition['description'] = $operation ? ($operation->getDescription() ?? '') : '';
133✔
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
110
        if (false === ($serializerContext[AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES] ?? true)) {
133✔
111
            $definition['additionalProperties'] = false;
×
112
        }
113

114
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
115
        if (Schema::VERSION_SWAGGER !== $version && $operation && $operation->getDeprecationReason()) {
133✔
116
            $definition['deprecated'] = true;
27✔
117
        } else {
118
            $definition['deprecated'] = false;
133✔
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
123
        if ($operation instanceof HttpOperation && ($operation->getTypes()[0] ?? null)) {
133✔
124
            $definition['externalDocs'] = ['url' => $operation->getTypes()[0]];
35✔
125
        }
126

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

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

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

142
        return $schema;
133✔
143
    }
144

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

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

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

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

170
            return;
47✔
171
        }
172

173
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
125✔
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)
178
        $propertySchemaType = $propertySchema['type'] ?? false;
125✔
179

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

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

194
            return;
99✔
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
199
        $version = $schema->getVersion();
111✔
200
        $refs = [];
111✔
201
        $isNullable = null;
111✔
202

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

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

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

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

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

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

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

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

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

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

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

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

263
        return \is_array($groups) ? $groups : [$groups];
125✔
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
    {
271
        $options = [
133✔
272
            /* @see https://github.com/symfony/symfony/blob/v5.1.0/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php */
273
            'enable_getter_setter_extraction' => true,
133✔
274
        ];
133✔
275

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

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

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

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

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

297
        return $options;
133✔
298
    }
299

300
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
301
    {
302
        $this->schemaFactory = $schemaFactory;
1,769✔
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