Completed
Push — master ( 9298c4...e8effc )
by Kévin
08:23 queued 12s
created

SchemaFactory::buildDefinitionName()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
c 1
b 0
f 0
nc 24
nop 6
dl 0
loc 24
rs 8.8333
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
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\Core\JsonSchema;
15
16
use ApiPlatform\Core\Api\OperationType;
17
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
18
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
19
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
20
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
21
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
22
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
23
use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
24
use ApiPlatform\Core\Util\ResourceClassInfoTrait;
25
use Symfony\Component\PropertyInfo\Type;
26
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
27
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
28
29
/**
30
 * {@inheritdoc}
31
 *
32
 * @experimental
33
 *
34
 * @author Kévin Dunglas <[email protected]>
35
 */
36
final class SchemaFactory implements SchemaFactoryInterface
37
{
38
    use ResourceClassInfoTrait;
39
40
    private $typeFactory;
41
    private $propertyNameCollectionFactory;
42
    private $propertyMetadataFactory;
43
    private $nameConverter;
44
    private $distinctFormats = [];
45
46
    public function __construct(TypeFactoryInterface $typeFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, NameConverterInterface $nameConverter = null, ResourceClassResolverInterface $resourceClassResolver = null)
47
    {
48
        $this->typeFactory = $typeFactory;
49
        $this->resourceMetadataFactory = $resourceMetadataFactory;
50
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
51
        $this->propertyMetadataFactory = $propertyMetadataFactory;
52
        $this->nameConverter = $nameConverter;
53
        $this->resourceClassResolver = $resourceClassResolver;
54
    }
55
56
    /**
57
     * When added to the list, the given format will lead to the creation of a new definition.
58
     *
59
     * @internal
60
     */
61
    public function addDistinctFormat(string $format): void
62
    {
63
        $this->distinctFormats[$format] = true;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?string $operationType = null, ?string $operationName = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema
70
    {
71
        $schema = $schema ?? new Schema();
72
        if (null === $metadata = $this->getMetadata($className, $type, $operationType, $operationName, $serializerContext)) {
73
            return $schema;
74
        }
75
        [$resourceMetadata, $serializerContext, $inputOrOutputClass] = $metadata;
76
77
        if (null === $resourceMetadata && (null !== $operationType || null !== $operationName)) {
78
            throw new \LogicException('The $operationType and $operationName arguments must be null for non-resource class.');
79
        }
80
81
        $version = $schema->getVersion();
82
        $definitionName = $this->buildDefinitionName($className, $format, $type, $operationType, $operationName, $serializerContext);
83
84
        if (null === $operationType || null === $operationName) {
85
            $method = Schema::TYPE_INPUT === $type ? 'POST' : 'GET';
86
        } else {
87
            $method = $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'method');
88
        }
89
90
        if (Schema::TYPE_OUTPUT !== $type && !\in_array($method, ['POST', 'PATCH', 'PUT'], true)) {
91
            return $schema;
92
        }
93
94
        if (!isset($schema['$ref']) && !isset($schema['type'])) {
95
            $ref = Schema::VERSION_OPENAPI === $version ? '#/components/schemas/'.$definitionName : '#/definitions/'.$definitionName;
96
97
            $method = null !== $operationType && null !== $operationName ? $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'method', 'GET') : 'GET';
98
            if ($forceCollection || (OperationType::COLLECTION === $operationType && 'POST' !== $method)) {
99
                $schema['type'] = 'array';
100
                $schema['items'] = ['$ref' => $ref];
101
            } else {
102
                $schema['$ref'] = $ref;
103
            }
104
        }
105
106
        $definitions = $schema->getDefinitions();
107
        if (isset($definitions[$definitionName])) {
108
            // Already computed
109
            return $schema;
110
        }
111
112
        $definition = new \ArrayObject(['type' => 'object']);
113
        $definitions[$definitionName] = $definition;
114
        if (null !== $resourceMetadata && null !== $description = $resourceMetadata->getDescription()) {
115
            $definition['description'] = $description;
116
        }
117
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
118
        if (
119
            Schema::VERSION_SWAGGER !== $version &&
120
            null !== $resourceMetadata &&
121
            (
122
                (null !== $operationType && null !== $operationName && null !== $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'deprecation_reason', null, true)) ||
123
                null !== $resourceMetadata->getAttribute('deprecation_reason', null)
124
            )
125
        ) {
126
            $definition['deprecated'] = true;
127
        }
128
        // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
129
        // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
130
        if (null !== $resourceMetadata && null !== $iri = $resourceMetadata->getIri()) {
131
            $definition['externalDocs'] = ['url' => $iri];
132
        }
133
134
        $options = isset($serializerContext[AbstractNormalizer::GROUPS]) ? ['serializer_groups' => (array) $serializerContext[AbstractNormalizer::GROUPS]] : [];
135
        foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) {
136
            $propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName);
137
            if (!$propertyMetadata->isReadable() && !$propertyMetadata->isWritable()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyMetadata->isWritable() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
Bug Best Practice introduced by
The expression $propertyMetadata->isReadable() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
138
                continue;
139
            }
140
141
            $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $inputOrOutputClass, $format, $serializerContext) : $propertyName;
0 ignored issues
show
Unused Code introduced by
The call to Symfony\Component\Serial...rInterface::normalize() has too many arguments starting with $inputOrOutputClass. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

141
            $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->/** @scrutinizer ignore-call */ normalize($propertyName, $inputOrOutputClass, $format, $serializerContext) : $propertyName;

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
142
            if ($propertyMetadata->isRequired()) {
143
                $definition['required'][] = $normalizedPropertyName;
144
            }
145
146
            $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format);
147
        }
148
149
        return $schema;
150
    }
151
152
    private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, PropertyMetadata $propertyMetadata, array $serializerContext, string $format): void
153
    {
154
        $version = $schema->getVersion();
155
        $swagger = false;
156
        switch ($version) {
157
            case Schema::VERSION_SWAGGER:
158
                $swagger = true;
159
                $basePropertySchemaAttribute = 'swagger_context';
160
                break;
161
            case Schema::VERSION_OPENAPI:
162
                $basePropertySchemaAttribute = 'openapi_context';
163
                break;
164
            default:
165
                $basePropertySchemaAttribute = 'json_schema_context';
166
        }
167
168
        $propertySchema = $propertyMetadata->getAttributes()[$basePropertySchemaAttribute] ?? [];
169
        if (false === $propertyMetadata->isWritable() && !$propertyMetadata->isInitializable()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyMetadata->isInitializable() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
170
            $propertySchema['readOnly'] = true;
171
        }
172
        if (!$swagger && false === $propertyMetadata->isReadable()) {
173
            $propertySchema['writeOnly'] = true;
174
        }
175
        if (null !== $description = $propertyMetadata->getDescription()) {
176
            $propertySchema['description'] = $description;
177
        }
178
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
179
        if (!$swagger && null !== $propertyMetadata->getAttribute('deprecation_reason')) {
180
            $propertySchema['deprecated'] = true;
181
        }
182
        // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
183
        // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
184
        if (null !== $iri = $propertyMetadata->getIri()) {
185
            $propertySchema['externalDocs'] = ['url' => $iri];
186
        }
187
188
        if (!isset($propertySchema['default']) && null !== $default = $propertyMetadata->getDefault()) {
189
            $propertySchema['default'] = $default;
190
        }
191
192
        if (!isset($propertySchema['example']) && null !== $example = $propertyMetadata->getExample()) {
193
            $propertySchema['example'] = $example;
194
        }
195
196
        if (!isset($propertySchema['example']) && isset($propertySchema['default'])) {
197
            $propertySchema['example'] = $propertySchema['default'];
198
        }
199
200
        $valueSchema = [];
201
        if (null !== $type = $propertyMetadata->getType()) {
202
            $isCollection = $type->isCollection();
203
            if (null === $valueType = $isCollection ? $type->getCollectionValueType() : $type) {
204
                $builtinType = 'string';
205
                $className = null;
206
            } else {
207
                $builtinType = $valueType->getBuiltinType();
208
                $className = $valueType->getClassName();
209
            }
210
211
            $valueSchema = $this->typeFactory->getType(new Type($builtinType, $type->isNullable(), $className, $isCollection), $format, $propertyMetadata->isReadableLink(), $serializerContext, $schema);
212
        }
213
214
        $propertySchema = new \ArrayObject($propertySchema + $valueSchema);
215
        if (DocumentationNormalizer::OPENAPI_VERSION === $version) {
216
            $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = $propertySchema;
217
218
            return;
219
        }
220
221
        $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = $propertySchema;
222
    }
223
224
    private function buildDefinitionName(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?string $operationType = null, ?string $operationName = null, ?array $serializerContext = null): string
225
    {
226
        [$resourceMetadata, $serializerContext, $inputOrOutputClass] = $this->getMetadata($className, $type, $operationType, $operationName, $serializerContext);
227
228
        $prefix = $resourceMetadata ? $resourceMetadata->getShortName() : (new \ReflectionClass($className))->getShortName();
229
        if (null !== $inputOrOutputClass && $className !== $inputOrOutputClass) {
230
            $parts = explode('\\', $inputOrOutputClass);
231
            $shortName = end($parts);
232
            $prefix .= ':'.$shortName;
233
        }
234
235
        if (isset($this->distinctFormats[$format])) {
236
            // JSON is the default, and so isn't included in the definition name
237
            $prefix .= ':'.$format;
238
        }
239
240
        if (isset($serializerContext[DocumentationNormalizer::SWAGGER_DEFINITION_NAME])) {
241
            $name = sprintf('%s-%s', $prefix, $serializerContext[DocumentationNormalizer::SWAGGER_DEFINITION_NAME]);
242
        } else {
243
            $groups = (array) ($serializerContext[AbstractNormalizer::GROUPS] ?? []);
244
            $name = $groups ? sprintf('%s-%s', $prefix, implode('_', $groups)) : $prefix;
0 ignored issues
show
introduced by
$groups is an empty array, thus is always false.
Loading history...
245
        }
246
247
        return $name;
248
    }
249
250
    private function getMetadata(string $className, string $type = Schema::TYPE_OUTPUT, ?string $operationType, ?string $operationName, ?array $serializerContext): ?array
251
    {
252
        if (!$this->isResourceClass($className)) {
253
            return [
254
                null,
255
                $serializerContext ?? [],
256
                $className,
257
            ];
258
        }
259
260
        $resourceMetadata = $this->resourceMetadataFactory->create($className);
0 ignored issues
show
Bug introduced by
The method create() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

260
        /** @scrutinizer ignore-call */ 
261
        $resourceMetadata = $this->resourceMetadataFactory->create($className);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
261
        $attribute = Schema::TYPE_OUTPUT === $type ? 'output' : 'input';
262
        if (null === $operationType || null === $operationName) {
263
            $inputOrOutput = $resourceMetadata->getAttribute($attribute, ['class' => $className]);
264
        } else {
265
            $inputOrOutput = $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, $attribute, ['class' => $className], true);
266
        }
267
268
        if (null === ($inputOrOutput['class'] ?? null)) {
269
            // input or output disabled
270
            return null;
271
        }
272
273
        return [
274
            $resourceMetadata,
275
            $serializerContext ?? $this->getSerializerContext($resourceMetadata, $type, $operationType, $operationName),
276
            $inputOrOutput['class'],
277
        ];
278
    }
279
280
    private function getSerializerContext(ResourceMetadata $resourceMetadata, string $type = Schema::TYPE_OUTPUT, ?string $operationType, ?string $operationName): array
281
    {
282
        $attribute = Schema::TYPE_OUTPUT === $type ? 'normalization_context' : 'denormalization_context';
283
284
        if (null === $operationType || null === $operationName) {
285
            return $resourceMetadata->getAttribute($attribute, []);
286
        }
287
288
        return $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, $attribute, [], true);
289
    }
290
}
291