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

api-platform / core / 13175309672

06 Feb 2025 09:04AM UTC coverage: 7.663% (-0.2%) from 7.841%
13175309672

push

github

web-flow
fix: ensure template files have a tpl file extension (#6826) (#6829)

2 of 5 new or added lines in 4 files covered. (40.0%)

3676 existing lines in 122 files now uncovered.

13073 of 170593 relevant lines covered (7.66%)

27.3 hits per line

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

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

48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
2,298✔
49
        $this->resourceClassResolver = $resourceClassResolver;
2,298✔
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();
189✔
58

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

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

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

78
        $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
189✔
79
        if (!$operation) {
189✔
80
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
114✔
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)) {
189✔
85
            return $schema;
15✔
86
        }
87

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

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

104
        /** @var \ArrayObject<string, mixed> $definition */
105
        $definition = new \ArrayObject(['type' => 'object']);
189✔
106
        $definitions[$definitionName] = $definition;
189✔
107
        $definition['description'] = $operation ? ($operation->getDescription() ?? '') : '';
189✔
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)) {
189✔
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()) {
189✔
117
            $definition['deprecated'] = true;
39✔
118
        } else {
119
            $definition['deprecated'] = false;
189✔
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)) {
189✔
125
            $definition['externalDocs'] = ['url' => $operation->getTypes()[0]];
51✔
126
        }
127

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

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

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

143
        return $schema;
189✔
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();
177✔
149
        if (Schema::VERSION_SWAGGER === $version || Schema::VERSION_OPENAPI === $version) {
177✔
150
            $additionalPropertySchema = $propertyMetadata->getOpenapiContext();
60✔
151
        } else {
152
            $additionalPropertySchema = $propertyMetadata->getJsonSchemaContext();
117✔
153
        }
154

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

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

165
        $extraProperties = $propertyMetadata->getExtraProperties() ?? [];
177✔
166
        // see AttributePropertyMetadataFactory
167
        if (true === ($extraProperties[SchemaPropertyMetadataFactory::JSON_SCHEMA_USER_DEFINED] ?? false)) {
177✔
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);
18✔
170

171
            return;
18✔
172
        }
173

174
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
177✔
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;
177✔
180

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

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

195
            return;
141✔
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();
156✔
201
        $refs = [];
156✔
202
        $isNullable = null;
156✔
203

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

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

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

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

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

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

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

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

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

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

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

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

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

277
        if (isset($serializerContext[AbstractNormalizer::GROUPS])) {
189✔
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];
78✔
280
        }
281

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

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

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

294
        return $options;
189✔
295
    }
296

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