Passed
Pull Request — master (#2983)
by Kévin
04:26
created

SchemaBuilder::buildDefinitionName()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
c 0
b 0
f 0
nc 13
nop 7
dl 0
loc 27
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\Exception\ResourceClassNotFoundException;
17
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
18
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
19
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
20
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
21
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
22
use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
23
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
24
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
25
26
/**
27
 * Builds an OpenAPI Schema, an extended subset of the JSON Schema Specification.
28
 *
29
 * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schema-object
30
 * @see https://tools.ietf.org/html/draft-wright-json-schema-01
31
 *
32
 * @author Kévin Dunglas <[email protected]>
33
 */
34
final class SchemaBuilder
35
{
36
    use TypeResolverTrait;
37
38
    private $resourceMetadataFactory;
39
    private $propertyNameCollectionFactory;
40
    private $propertyMetadataFactory;
41
    private $nameConverter;
42
43
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, NameConverterInterface $nameConverter = null)
44
    {
45
        $this->resourceMetadataFactory = $resourceMetadataFactory;
46
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
47
        $this->propertyMetadataFactory = $propertyMetadataFactory;
48
        $this->nameConverter = $nameConverter;
49
    }
50
51
    /**
52
     * @throws ResourceClassNotFoundException
53
     */
54
    public function buildSchema(string $resourceClass, string $format = 'json', bool $output = true, ?string $operationType = null, ?string $operationName = null, ?Schema $baseSchema = null, ?array $serializerContext = null): Schema
55
    {
56
        if (null === $metadata = $this->getMetadata($resourceClass, $output, $operationType, $operationName, $serializerContext)) {
57
            return $baseSchema ?? new Schema();
58
        }
59
60
        [$resourceMetadata, $serializerContext, $inputOrOutputClass] = $metadata;
61
62
        $definitionName = $this->buildDefinitionName($resourceClass, $format, $output, $operationType, $operationName, $serializerContext);
63
        if (null === $baseSchema || null === $rootDefinitionName = $baseSchema->getRootDefinitionId()) {
64
            $rootDefinitionName = $definitionName;
65
        }
66
67
        if ($baseSchema) {
68
            $version = $baseSchema->getVersion();
69
            $schema = new Schema($version, $baseSchema->getSchema(), $rootDefinitionName, $baseSchema->getDefinitions());
70
        } else {
71
            $version = Schema::VERSION_JSON_SCHEMA;
72
            $schema = new Schema($version, null, $rootDefinitionName);
73
        }
74
75
        $definitions = $schema->getDefinitions();
76
        if (isset($definitions[$definitionName])) {
77
            // Already computed
78
            return $schema;
79
        }
80
81
        $definition = new \ArrayObject(['type' => 'object']);
82
        $definitions[$definitionName] = $definition;
83
        if (null !== $description = $resourceMetadata->getDescription()) {
84
            $definition['description'] = $description;
85
        }
86
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
87
        if (
88
            Schema::VERSION_SWAGGER !== $version &&
89
            (
90
                (null !== $operationType && null !== $operationName && null !== $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'deprecation_reason', null, true)) ||
91
                null !== $resourceMetadata->getAttribute('deprecation_reason', null)
92
            )
93
        ) {
94
            $definition['deprecated'] = true;
95
        }
96
        // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
97
        // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
98
        if (null !== $iri = $resourceMetadata->getIri()) {
99
            $definition['externalDocs'] = ['url' => $iri];
100
        }
101
102
        $options = isset($serializerContext[AbstractNormalizer::GROUPS]) ? ['serializer_groups' => $serializerContext[AbstractNormalizer::GROUPS]] : [];
103
        foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) {
104
            $propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName);
105
            if (!$propertyMetadata->isReadable() && !$propertyMetadata->isWritable()) {
0 ignored issues
show
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...
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...
106
                continue;
107
            }
108
109
            $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

109
            $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...
110
            if ($propertyMetadata->isRequired()) {
111
                $definition['required'][] = $normalizedPropertyName;
112
            }
113
114
            $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format);
115
        }
116
117
        return $schema;
118
    }
119
120
    private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, PropertyMetadata $propertyMetadata, array $serializerContext, string $format): void
121
    {
122
        $version = $schema->getVersion();
123
        $swagger = false;
124
        switch ($version) {
125
            case Schema::VERSION_SWAGGER:
126
                $swagger = true;
127
                $basePropertySchemaAttribute = 'swagger_context';
128
                break;
129
            case Schema::VERSION_OPENAPI:
130
                $basePropertySchemaAttribute = 'openapi_context';
131
                break;
132
            default:
133
                $basePropertySchemaAttribute = 'json_schema_context';
134
        }
135
136
        $propertySchema = $propertyMetadata->getAttributes()[$basePropertySchemaAttribute] ?? [];
137
        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...
138
            $propertySchema['readOnly'] = true;
139
        }
140
        if (!$swagger && false === $propertyMetadata->isReadable()) {
141
            $propertySchema['writeOnly'] = true;
142
        }
143
        if (null !== $description = $propertyMetadata->getDescription()) {
144
            $propertySchema['description'] = $description;
145
        }
146
        // see https://github.com/json-schema-org/json-schema-spec/pull/737
147
        if (!$swagger && null !== $propertyMetadata->getAttribute('deprecation_reason')) {
148
            $propertySchema['deprecated'] = true;
149
        }
150
        // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
151
        // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
152
        if (null !== $iri = $propertyMetadata->getIri()) {
153
            $propertySchema['externalDocs'] = ['url' => $iri];
154
        }
155
156
        $valueSchema = [];
157
        if (null !== $type = $propertyMetadata->getType()) {
158
            $isCollection = $type->isCollection();
159
            if (null === $valueType = $isCollection ? $type->getCollectionValueType() : $type) {
160
                $builtinType = 'string';
161
                $className = null;
162
            } else {
163
                $builtinType = $valueType->getBuiltinType();
164
                $className = $valueType->getClassName();
165
            }
166
167
            $valueSchema = $this->getType($builtinType, $isCollection, $className, $format, $propertyMetadata->isReadableLink(), $serializerContext, $schema);
168
        }
169
170
        $propertySchema = new \ArrayObject($propertySchema + $valueSchema);
171
        if (DocumentationNormalizer::OPENAPI_VERSION === $version) {
172
            $schema['components']['schemas'][$definitionName]['properties'][$normalizedPropertyName] = $propertySchema;
173
174
            return;
175
        }
176
177
        $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = $propertySchema;
178
    }
179
180
    private function buildDefinitionName(string $resourceClass, string $format = 'json', bool $output = true, ?string $operationType = null, ?string $operationName = null, ?array $serializerContext = null, string $version = DocumentationNormalizer::OPENAPI_VERSION): ?string
0 ignored issues
show
Unused Code introduced by
The parameter $version is not used and could be removed. ( Ignorable by Annotation )

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

180
    private function buildDefinitionName(string $resourceClass, string $format = 'json', bool $output = true, ?string $operationType = null, ?string $operationName = null, ?array $serializerContext = null, /** @scrutinizer ignore-unused */ string $version = DocumentationNormalizer::OPENAPI_VERSION): ?string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
181
    {
182
        if (null === $metadata = $this->getMetadata($resourceClass, $output, $operationType, $operationName, $serializerContext)) {
183
            return null;
184
        }
185
        [$resourceMetadata, $serializerContext, $inputOrOutputClass] = $metadata;
186
187
        $prefix = $resourceMetadata->getShortName();
188
        if (null !== $inputOrOutputClass && $resourceClass !== $inputOrOutputClass) {
189
            $prefix .= ':'.md5($inputOrOutputClass);
190
        }
191
192
        if ('json' !== $format) {
193
            // We don't include JSON in the definition name because:
194
            // * it necessary to preserve backward compatibility with Swagger\DocumentationNormalizer's generated names
195
            // * it's the default (so it's useless)
196
            $prefix .= ':'.$format;
197
        }
198
199
        if (isset($serializerContext[DocumentationNormalizer::SWAGGER_DEFINITION_NAME])) {
200
            $name = sprintf('%s-%s', $prefix, $serializerContext[DocumentationNormalizer::SWAGGER_DEFINITION_NAME]);
201
        } else {
202
            $groups = (array) ($serializerContext[AbstractNormalizer::GROUPS] ?? []);
203
            $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...
204
        }
205
206
        return $name;
207
    }
208
209
    private function getMetadata(string $resourceClass, bool $output, ?string $operationType, ?string $operationName, ?array $serializerContext): ?array
210
    {
211
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
212
        $attribute = $output ? 'output' : 'input';
213
        if (null === $operationType || null === $operationName) {
214
            $inputOrOutput = $resourceMetadata->getAttribute($attribute, ['class' => $resourceClass]);
215
        } else {
216
            $inputOrOutput = $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, $attribute, ['class' => $resourceClass], true);
217
        }
218
219
        if (null === ($inputOrOutput['class'] ?? null)) {
220
            // input or output disabled
221
            return null;
222
        }
223
224
        return [
225
            $resourceMetadata,
226
            $serializerContext ?? $this->getSerializerContext($resourceMetadata, $output, $operationType, $operationName),
227
            $inputOrOutput['class'],
228
        ];
229
    }
230
231
    private function getSerializerContext(ResourceMetadata $resourceMetadata, bool $output, ?string $operationType, ?string $operationName): array
232
    {
233
        $attribute = $output ? 'normalization_context' : 'denormalization_context';
234
235
        if (null === $operationType || null === $operationName) {
236
            return $resourceMetadata->getAttribute($attribute, []);
237
        }
238
239
        return $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, $attribute, [], true);
240
    }
241
}
242