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

api-platform / core / 10010837821

19 Jul 2024 03:54PM UTC coverage: 64.225% (-0.5%) from 64.689%
10010837821

push

github

web-flow
chore: missing deprecations (#6480)

50 of 228 new or added lines in 14 files covered. (21.93%)

186 existing lines in 31 files now uncovered.

11549 of 17982 relevant lines covered (64.23%)

68.6 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
    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) {
564✔
45
            trigger_deprecation('api-platform/core', '3.4', sprintf('Injecting the "%s" inside "%s" is deprecated and "%s" will be removed in 4.x.', TypeFactoryInterface::class, self::class, TypeFactoryInterface::class));
508✔
46
            $this->typeFactory = $typeFactory;
508✔
47
        }
48
        if (!$definitionNameFactory) {
564✔
UNCOV
49
            $this->definitionNameFactory = new DefinitionNameFactory($this->distinctFormats);
×
50
        }
51

52
        $this->resourceMetadataFactory = $resourceMetadataFactory;
564✔
53
        $this->resourceClassResolver = $resourceClassResolver;
564✔
54
    }
55

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

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

73
        if (null === $inputOrOutputClass) {
228✔
74
            // input or output disabled
75
            return $schema;
28✔
76
        }
77

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

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

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

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

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

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

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

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

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

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

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

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

147
        return $schema;
228✔
148
    }
149

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

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

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

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

175
            return;
32✔
176
        }
177

178
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
172✔
179

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

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

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

198
            return;
120✔
199
        }
200

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

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

211
            // 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
212
            if ($typeFromFactory = $this->typeFactory?->getType($type, 'jsonschema', $propertyMetadata->isReadableLink(), $serializerContext)) {
144✔
213
                $propertySchema = $typeFromFactory;
32✔
214
                break;
32✔
215
            }
216

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

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

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

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

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

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

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

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

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

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

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

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

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

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

294
        return $options;
228✔
295
    }
296

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

© 2026 Coveralls, Inc