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

api-platform / core / 13814792797

12 Mar 2025 03:09PM UTC coverage: 5.889% (-1.4%) from 7.289%
13814792797

Pull #7012

github

web-flow
Merge 199d44919 into 284937039
Pull Request #7012: doc: comment typo in ApiResource.php

10048 of 170615 relevant lines covered (5.89%)

5.17 hits per line

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

94.57
/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) {
441✔
45
            $this->definitionNameFactory = new DefinitionNameFactory($this->distinctFormats);
×
46
        }
47

48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
441✔
49
        $this->resourceClassResolver = $resourceClassResolver;
441✔
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();
150✔
58

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

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

74
        $validationGroups = $operation ? $this->getValidationGroups($operation) : [];
150✔
75
        $version = $schema->getVersion();
150✔
76
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
150✔
77

78
        $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
150✔
79
        if (!$operation) {
150✔
80
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
75✔
81
        }
82

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

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

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

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

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

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

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

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

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

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

143
        return $schema;
150✔
144
    }
145

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

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

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

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

171
            return;
3✔
172
        }
173

174
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
138✔
175

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

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

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

195
            return;
102✔
196
        }
197

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

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

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

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

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

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

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

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

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

245
        if ($isNullable) {
117✔
246
            $refs[] = ['type' => 'null'];
42✔
247
        }
248

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

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

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

264
        return \is_array($groups) ? $groups : [$groups];
138✔
265
    }
266

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

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

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

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

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

294
        return $options;
150✔
295
    }
296

297
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
298
    {
299
        $this->schemaFactory = $schemaFactory;
441✔
300
    }
301
}
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