Completed
Pull Request — master (#591)
by Amrouche
03:52
created

ApiDocumentationBuilder::getRange()   C

Complexity

Conditions 12
Paths 19

Size

Total Lines 43
Code Lines 27

Duplication

Lines 43
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 43
loc 43
rs 5.1612
cc 12
eloc 27
nc 19
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
namespace ApiPlatform\Core\Swagger;
13
14
use ApiPlatform\Core\Api\IriConverterInterface;
15
use ApiPlatform\Core\Api\OperationMethodResolverInterface;
16
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
17
use ApiPlatform\Core\Api\UrlGeneratorInterface;
18
use ApiPlatform\Core\Documentation\ApiDocumentationBuilderInterface;
19
use ApiPlatform\Core\Exception\InvalidArgumentException;
20
use ApiPlatform\Core\JsonLd\ContextBuilderInterface;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
24
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
25
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
26
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
27
use Symfony\Component\PropertyInfo\Type;
28
29
/**
30
 * Creates a machine readable Swagger API documentation.
31
 *
32
 * @author Kévin Dunglas <[email protected]>
33
 */
34
final class ApiDocumentationBuilder implements ApiDocumentationBuilderInterface
35
{
36
    private $resourceNameCollectionFactory;
37
    private $resourceMetadataFactory;
38
    private $propertyNameCollectionFactory;
39
    private $propertyMetadataFactory;
40
    private $contextBuilder;
41
    private $resourceClassResolver;
42
    private $operationMethodResolver;
43
    private $urlGenerator;
44
    private $title;
45
    private $description;
46
    private $iriConverter;
47
    private $version;
48
    private $host;
49
    private $schema;
50
51
    public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ContextBuilderInterface $contextBuilder, ResourceClassResolverInterface $resourceClassResolver, OperationMethodResolverInterface $operationMethodResolver, UrlGeneratorInterface $urlGenerator, IriConverterInterface $iriConverter, string $title = '', string $description = '', string $version = null, string $host, string $schema)
52
    {
53
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
54
        $this->resourceMetadataFactory = $resourceMetadataFactory;
55
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
56
        $this->propertyMetadataFactory = $propertyMetadataFactory;
57
        $this->contextBuilder = $contextBuilder;
58
        $this->resourceClassResolver = $resourceClassResolver;
59
        $this->operationMethodResolver = $operationMethodResolver;
60
        $this->urlGenerator = $urlGenerator;
61
        $this->title = $title;
62
        $this->description = $description;
63
        $this->iriConverter = $iriConverter;
64
        $this->version = $version;
65
        $this->host = $host;
66
        $this->schema[] = $schema;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getApiDocumentation()
73
    {
74
        $classes = [];
75
        $itemOperations = [];
76
        $itemOperations['operation'] = [];
77
78
        $itemOperationsDocs = [];
79
        $properties = [];
80
81
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
82
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
83
84
            $shortName = $resourceMetadata->getShortName();
85
            $prefixedShortName = ($iri = $resourceMetadata->getIri()) ? $iri : '#'.$shortName;
86
87
            $class = [
88
                'name' => $shortName,
89
                'externalDocs' => [
90
                    'url' => $prefixedShortName,
91
                ],
92
            ];
93
94
            if ($description = $resourceMetadata->getDescription()) {
95
                $class = [
96
                    'name' => $shortName,
97
                    'description' => $description,
98
                    'externalDocs' => [
99
                        'url' => $prefixedShortName,
100
                    ],
101
                ];
102
            }
103
104
            $attributes = $resourceMetadata->getAttributes();
105
            $context = [];
106
107
            if (isset($attributes['normalization_context']['groups'])) {
108
                $context['serializer_groups'] = $attributes['normalization_context']['groups'];
109
            }
110
111 View Code Duplication
            if (isset($attributes['denormalization_context']['groups'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
                $context['serializer_groups'] = isset($context['serializer_groups']) ? array_merge($context['serializer_groups'], $attributes['denormalization_context']['groups']) : $context['serializer_groups'];
113
            }
114
115
            foreach ($this->propertyNameCollectionFactory->create($resourceClass, $context) as $propertyName) {
116
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
117
118
                if ($propertyMetadata->isIdentifier() && !$propertyMetadata->isWritable()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyMetadata->isWritable() of type null|boolean 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...
119
                    continue;
120
                }
121
                $range = $this->getRange($propertyMetadata);
122
123
                $property[$propertyName] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$property was never initialized. Although not strictly required by PHP, it is generally a good practice to add $property = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
124
                    'type' => $range,
125
                ];
126
127
                if (is_array($range)) {
128
                    $property[$propertyName] = $range;
0 ignored issues
show
Bug introduced by
The variable $property does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
129
                }
130
131
                $required = [];
132
133
                if ($propertyMetadata->isRequired()) {
134
                    $required = array_merge($required, [$propertyName]);
135
                }
136
137
                if (0 !== count($required)) {
138
                    $properties[$shortName]['required'] = $required;
139
                }
140
141
                $properties[$shortName]['type'] = 'object';
142
                $properties[$shortName]['properties'] = $property;
143
            }
144
145
            if ($operations = $resourceMetadata->getItemOperations()) {
146
                foreach ($operations as $operationName => $itemOperation) {
147
                    $swaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $operationName, $itemOperation, $prefixedShortName, false);
148
                    $itemOperations['operation'] = array_merge($itemOperations['operation'], $swaggerOperation);
149
                }
150
            }
151
152
            try {
153
                $resourceClassIri = $this->iriConverter->getIriFromResourceClass($resourceClass);
154
            } catch (InvalidArgumentException $e) {
155
                $resourceClassIri = '/nopaths';
156
            }
157
            $resourceClassIri .= '/{id}';
158
159
            $itemOperationsDocs[$resourceClassIri] = $itemOperations['operation'];
160
            $classes[] = $class;
161
        }
162
163
        $doc['swagger'] = '2.0';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$doc was never initialized. Although not strictly required by PHP, it is generally a good practice to add $doc = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
164
        if ('' !== $this->title) {
165
            $doc['info']['title'] = $this->title;
166
        }
167
168
        if ('' !== $this->description) {
169
            $doc['info']['description'] = $this->description;
170
        }
171
        $doc['info']['version'] = $this->version ?? '0.0.0';
172
        $doc['host'] = $this->host;
173
        $doc['basePath'] = $this->urlGenerator->generate('api_jsonld_entrypoint');
174
        $doc['definitions'] = $properties;
175
        $doc['externalDocs'] = ['description' => 'Find more about api-platform', 'url' => 'docs'];
176
        $doc['tags'] = $classes;
177
        $doc['schemes'] = $this->schema; // more schema ?
178
        $doc['paths'] = $itemOperationsDocs;
179
180
        return $doc;
181
    }
182
183
    /**
184
     * Gets and populates if applicable a Swagger operation.
185
     */
186
    private function getSwaggerOperation(string $resourceClass, ResourceMetadata $resourceMetadata, string $operationName, array $operation, string $prefixedShortName, bool $collection) : array
0 ignored issues
show
Unused Code introduced by
The parameter $prefixedShortName is not used and could be removed.

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

Loading history...
187
    {
188 View Code Duplication
        if ($collection) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
189
            $method = $this->operationMethodResolver->getCollectionOperationMethod($resourceClass, $operationName);
190
        } else {
191
            $method = $this->operationMethodResolver->getItemOperationMethod($resourceClass, $operationName);
192
        }
193
        $methodSwagger = strtolower($method);
194
        $swaggerOperation = $operation['swagger_context'] ?? [];
195
        $shortName = $resourceMetadata->getShortName();
196
        $swaggerOperation[$methodSwagger] = [];
197
        $swaggerOperation[$methodSwagger]['tags'] = [$shortName];
198
        $swaggerOperation[$methodSwagger]['produces'] = ['application/json'];
199
        $swaggerOperation[$methodSwagger]['consumes'] = $swaggerOperation[$methodSwagger]['produces'];
200
        switch ($method) {
201
            case 'GET':
0 ignored issues
show
Coding Style introduced by
CASE statements must be defined using a colon

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
202
                if ($collection) {
203 View Code Duplication
                    if (!isset($swaggerOperation[$methodSwagger]['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
204
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves the collection of %s resources.', $shortName);
205
                    }
206
                } else {
207 View Code Duplication
                    if (!isset($swaggerOperation[$methodSwagger]['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
208
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves %s resource.', $shortName);
209
                    }
210
                    $swaggerOperation[$methodSwagger]['parameters'][] = [
211
                        'name' => 'id',
212
                        'in' => 'path',
213
                        'required' => true,
214
                        'type' => 'integer',
215
                    ];
216
                }
217
                $swaggerOperation[$methodSwagger]['responses'] = [
218
                    '200' => ['description' => 'Valid ID'],
219
                ];
220
                break;
221
222
            case 'POST':
0 ignored issues
show
Coding Style introduced by
CASE statements must be defined using a colon

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
223 View Code Duplication
                if (!isset($swaggerOperation[$methodSwagger]['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
224
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Creates a %s resource.', $shortName);
225
                }
226
                if ($this->resourceClassResolver->isResourceClass($shortName)) {
227
                    $swaggerOperation[$methodSwagger]['parameters'] = [
228
                        'in' => 'body',
229
                        'name' => 'body',
230
                        'description' => sprintf('%s resource to be added', $shortName),
231
                        'schema' => [
232
                            '$ref' => sprintf('#/definitions/%s', $shortName),
233
                        ],
234
                    ];
235
                }
236
237
                $swaggerOperation[$methodSwagger]['responses'] = [
238
                        '201' => ['description' => 'Valid ID'],
239
                    ];
240
241
            break;
242
243
            case 'PUT':
0 ignored issues
show
Coding Style introduced by
CASE statements must be defined using a colon

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
244 View Code Duplication
                if (!isset($swaggerOperation[$methodSwagger]['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Replaces the %s resource.', $shortName);
246
                }
247
                $swaggerOperation[$methodSwagger]['parameters'] = [[
248
                    'name' => 'id',
249
                    'in' => 'path',
250
                    'required' => true,
251
                    'type' => 'integer',
252
                ]];
253
                if ($this->resourceClassResolver->isResourceClass($shortName)) {
254
                    $swaggerOperation[$methodSwagger]['parameters'] = [[
255
                        'name' => 'id',
256
                        'in' => 'path',
257
                        'required' => true,
258
                        'type' => 'integer',
259
                    ],
260
                        [
261
                        'in' => 'body',
262
                        'name' => 'body',
263
                        'description' => sprintf('%s resource to be added', $shortName),
264
                        'schema' => [
265
                            '$ref' => sprintf('#/definitions/%s', $shortName),
266
                        ],
267
                    ], ];
268
                }
269
270
                $swaggerOperation[$methodSwagger]['responses'] = [
271
                    '200' => ['description' => 'Valid ID'],
272
                ];
273
274
            break;
275
            case 'DELETE':
276
                $swaggerOperation[$methodSwagger]['responses'] = [
277
                    '204' => ['description' => 'Deleted'],
278
                ];
279
                $swaggerOperation[$methodSwagger]['parameters'] = [[
280
                    'name' => 'id',
281
                    'in' => 'path',
282
                    'required' => true,
283
                    'type' => 'integer',
284
                ]];
285
            break;
286
        }
287
        ksort($swaggerOperation);
288
289
        return $swaggerOperation;
290
    }
291
292
    /**
293
     * Gets the range of the property.
294
     *
295
     * @param PropertyMetadata $propertyMetadata
296
     *
297
     * @return string|null
298
     */
299 View Code Duplication
    private function getRange(PropertyMetadata $propertyMetadata)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
300
    {
301
        $type = $propertyMetadata->getType();
302
        if (!$type) {
303
            return;
304
        }
305
306
        if ($type->isCollection() && $collectionType = $type->getCollectionValueType()) {
307
            $type = $collectionType;
308
        }
309
310
        switch ($type->getBuiltinType()) {
311
            case Type::BUILTIN_TYPE_STRING:
312
                return 'string';
313
314
            case Type::BUILTIN_TYPE_INT:
315
                return 'integer';
316
317
            case Type::BUILTIN_TYPE_FLOAT:
318
                return 'number';
319
320
            case Type::BUILTIN_TYPE_BOOL:
321
                return 'boolean';
322
323
            case Type::BUILTIN_TYPE_OBJECT:
324
                $className = $type->getClassName();
325
326
                if ($className) {
327
                    if (is_subclass_of($className, \DateTimeInterface::class)) {
1 ignored issue
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \DateTimeInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
328
                        return 'string';
329
                    }
330
331
                    $className = $type->getClassName();
332
                    if ($this->resourceClassResolver->isResourceClass($className)) {
333
                        return ['$ref' => sprintf('#/definitions/%s', $this->resourceMetadataFactory->create($className)->getShortName())];
334
                    }
335
                }
336
            break;
337
            default:
338
                return 'null';
339
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
340
        }
341
    }
342
}
343