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

api-platform / core / 14967870200

12 May 2025 08:47AM UTC coverage: 23.685% (+15.2%) from 8.477%
14967870200

push

github

web-flow
fix(serializer): invalid uri variable 400 response (#7135)

1 of 2 new or added lines in 2 files covered. (50.0%)

2825 existing lines in 152 files now uncovered.

11409 of 48169 relevant lines covered (23.69%)

54.89 hits per line

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

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

48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
1,284✔
49
        $this->resourceClassResolver = $resourceClassResolver;
1,284✔
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();
27✔
58

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

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

74
        $validationGroups = $operation ? $this->getValidationGroups($operation) : [];
27✔
75
        $version = $schema->getVersion();
27✔
76
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
27✔
77
        $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
27✔
78
        if (!$operation) {
27✔
79
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
27✔
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)) {
27✔
84
            return $schema;
15✔
85
        }
86

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

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

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

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

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

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

142
        return $schema;
27✔
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();
27✔
148
        if (Schema::VERSION_SWAGGER === $version || Schema::VERSION_OPENAPI === $version) {
27✔
149
            $additionalPropertySchema = $propertyMetadata->getOpenapiContext();
27✔
150
        } else {
UNCOV
151
            $additionalPropertySchema = $propertyMetadata->getJsonSchemaContext();
×
152
        }
153

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

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

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

170
            return;
27✔
171
        }
172

173
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
27✔
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;
27✔
179

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

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

194
            return;
27✔
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();
27✔
200
        $refs = [];
27✔
201
        $isNullable = null;
27✔
202

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

297
        return $options;
27✔
298
    }
299

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