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

api-platform / core / 10018803218

20 Jul 2024 08:17AM UTC coverage: 63.43% (-0.04%) from 63.469%
10018803218

push

github

web-flow
Revert "feat(jsonschema): make JSON-LD specific properties required (#6366)" (#6484)

This reverts commit aeca0149d.

2 of 2 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

11177 of 17621 relevant lines covered (63.43%)

53.37 hits per line

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

96.88
/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
    private ?TypeFactoryInterface $typeFactory = null;
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(?TypeFactoryInterface $typeFactory, 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 ($typeFactory) {
380✔
45
            $this->typeFactory = $typeFactory;
328✔
46
        }
47
        if (!$definitionNameFactory) {
380✔
48
            $this->definitionNameFactory = new DefinitionNameFactory($this->distinctFormats);
×
49
        }
50

51
        $this->resourceMetadataFactory = $resourceMetadataFactory;
380✔
52
        $this->resourceClassResolver = $resourceClassResolver;
380✔
53
    }
54

55
    /**
56
     * {@inheritdoc}
57
     */
58
    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
59
    {
60
        $schema = $schema ? clone $schema : new Schema();
212✔
61

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

72
        if (null === $inputOrOutputClass) {
212✔
73
            // input or output disabled
74
            return $schema;
24✔
75
        }
76

77
        $validationGroups = $operation ? $this->getValidationGroups($operation) : [];
212✔
78
        $version = $schema->getVersion();
212✔
79
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
212✔
80

81
        $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
212✔
82
        if (!$operation) {
212✔
83
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
60✔
84
        }
85

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

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

101
        $definitions = $schema->getDefinitions();
212✔
102
        if (isset($definitions[$definitionName])) {
212✔
103
            // Already computed
104
            return $schema;
24✔
105
        }
106

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

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

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

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

131
        $options = ['schema_type' => $type] + $this->getFactoryOptions($serializerContext, $validationGroups, $operation instanceof HttpOperation ? $operation : null);
212✔
132
        foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) {
212✔
133
            $propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName, $options);
160✔
134
            if (!$propertyMetadata->isReadable() && !$propertyMetadata->isWritable()) {
160✔
135
                continue;
32✔
136
            }
137

138
            $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $inputOrOutputClass, $format, $serializerContext) : $propertyName;
160✔
139
            if ($propertyMetadata->isRequired()) {
160✔
140
                $definition['required'][] = $normalizedPropertyName;
52✔
141
            }
142

143
            $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type);
160✔
144
        }
145

146
        return $schema;
212✔
147
    }
148

149
    private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void
150
    {
151
        $version = $schema->getVersion();
160✔
152
        if (Schema::VERSION_SWAGGER === $version || Schema::VERSION_OPENAPI === $version) {
160✔
153
            $additionalPropertySchema = $propertyMetadata->getOpenapiContext();
24✔
154
        } else {
155
            $additionalPropertySchema = $propertyMetadata->getJsonSchemaContext();
136✔
156
        }
157

158
        $propertySchema = array_merge(
160✔
159
            $propertyMetadata->getSchema() ?? [],
160✔
160
            $additionalPropertySchema ?? []
160✔
161
        );
160✔
162

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

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

174
            return;
28✔
175
        }
176

177
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
160✔
178

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

184
        $isUnknown = Schema::UNKNOWN_TYPE === $propertySchemaType
160✔
185
            || ('array' === $propertySchemaType && Schema::UNKNOWN_TYPE === ($propertySchema['items']['type'] ?? null));
160✔
186

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

197
            return;
108✔
198
        }
199

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

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

210
            // TODO: in 3.3 add trigger_deprecation() as type factories are not used anymore, we moved this logic to SchemaPropertyMetadataFactory so that it gets cached
211
            if ($typeFromFactory = $this->typeFactory?->getType($type, 'jsonschema', $propertyMetadata->isReadableLink(), $serializerContext)) {
136✔
212
                $propertySchema = $typeFromFactory;
28✔
213
                break;
28✔
214
            }
215

216
            $isCollection = $type->isCollection();
132✔
217
            if ($isCollection) {
132✔
218
                $valueType = $type->getCollectionValueTypes()[0] ?? null;
80✔
219
            } else {
220
                $valueType = $type;
132✔
221
            }
222

223
            $className = $valueType?->getClassName();
132✔
224
            if (null === $className) {
132✔
225
                continue;
132✔
226
            }
227

228
            $subSchemaFactory = $this->schemaFactory ?: $this;
72✔
229
            $subSchema = $subSchemaFactory->buildSchema($className, $format, $parentType, null, $subSchema, $serializerContext + [self::FORCE_SUBSCHEMA => true], false);
72✔
230
            if (!isset($subSchema['$ref'])) {
72✔
231
                continue;
24✔
232
            }
233

234
            if ($isCollection) {
72✔
235
                $propertySchema['items']['$ref'] = $subSchema['$ref'];
60✔
236
                unset($propertySchema['items']['type']);
60✔
237
                break;
60✔
238
            }
239

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

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

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

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

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

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

276
        if (isset($serializerContext[AbstractNormalizer::GROUPS])) {
212✔
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];
52✔
279
        }
280

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

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

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

293
        return $options;
212✔
294
    }
295

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

© 2026 Coveralls, Inc