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

ApiDocumentationBuilder::getSwaggerOperation()   D

Complexity

Conditions 13
Paths 28

Size

Total Lines 105
Code Lines 74

Duplication

Lines 17
Ratio 16.19 %

Importance

Changes 0
Metric Value
dl 17
loc 105
rs 4.9922
c 0
b 0
f 0
cc 13
eloc 74
nc 28
nop 6

How to fix   Long Method    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 Amrouche Hamza <[email protected]>
33
 * @author Kévin Dunglas <[email protected]>
34
 */
35
final class ApiDocumentationBuilder implements ApiDocumentationBuilderInterface
36
{
37
    private $resourceNameCollectionFactory;
38
    private $resourceMetadataFactory;
39
    private $propertyNameCollectionFactory;
40
    private $propertyMetadataFactory;
41
    private $contextBuilder;
42
    private $resourceClassResolver;
43
    private $operationMethodResolver;
44
    private $urlGenerator;
45
    private $title;
46
    private $description;
47
    private $iriConverter;
48
    private $version;
49
    private $host;
50
    private $schema;
51
    const SWAGGER_VERSION = '2.0';
52
    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)
53
    {
54
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
55
        $this->resourceMetadataFactory = $resourceMetadataFactory;
56
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
57
        $this->propertyMetadataFactory = $propertyMetadataFactory;
58
        $this->contextBuilder = $contextBuilder;
59
        $this->resourceClassResolver = $resourceClassResolver;
60
        $this->operationMethodResolver = $operationMethodResolver;
61
        $this->urlGenerator = $urlGenerator;
62
        $this->title = $title;
63
        $this->description = $description;
64
        $this->iriConverter = $iriConverter;
65
        $this->version = $version;
66
        $this->host = $host;
67
        $this->schema[] = $schema;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function getApiDocumentation()
74
    {
75
        $classes = [];
76
        $itemOperations = [];
77
        $itemOperations['operation'] = [];
78
79
        $itemOperationsDocs = [];
80
        $properties = [];
81
82
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
83
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
84
85
            $shortName = $resourceMetadata->getShortName();
86
            $prefixedShortName = ($iri = $resourceMetadata->getIri()) ? $iri : '#'.$shortName;
87
88
            $class = [
89
                'name' => $shortName,
90
                'externalDocs' => [
91
                    'url' => $prefixedShortName,
92
                ],
93
            ];
94
95
            if ($description = $resourceMetadata->getDescription()) {
96
                $class = [
97
                    'name' => $shortName,
98
                    'description' => $description,
99
                    'externalDocs' => [
100
                        'url' => $prefixedShortName,
101
                    ],
102
                ];
103
            }
104
105
            $attributes = $resourceMetadata->getAttributes();
106
            $context = [];
107
108
            if (isset($attributes['normalization_context']['groups'])) {
109
                $context['serializer_groups'] = $attributes['normalization_context']['groups'];
110
            }
111
112 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...
113
                $context['serializer_groups'] = isset($context['serializer_groups']) ? array_merge($context['serializer_groups'], $attributes['denormalization_context']['groups']) : $context['serializer_groups'];
114
            }
115
116
            foreach ($this->propertyNameCollectionFactory->create($resourceClass, $context) as $propertyName) {
117
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
118
119
                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...
120
                    continue;
121
                }
122
                $range = $this->getRange($propertyMetadata);
123
124
                $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...
125
                    'type' => $range,
126
                ];
127
128
                if (is_array($range)) {
129
                    $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...
130
                }
131
132
                $required = [];
133
134
                if ($propertyMetadata->isRequired()) {
135
                    $required = array_merge($required, [$propertyName]);
136
                }
137
138
                if (!empty($required)) {
139
                    $properties[$shortName]['required'] = $required;
140
                }
141
142
                $properties[$shortName]['type'] = 'object';
143
                $properties[$shortName]['properties'] = $property;
144
            }
145
146
            if ($operations = $resourceMetadata->getItemOperations()) {
147
                foreach ($operations as $operationName => $itemOperation) {
148
                    $swaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $operationName, $itemOperation, $prefixedShortName, false);
149
                    $itemOperations['operation'] = array_merge($itemOperations['operation'], $swaggerOperation);
150
                }
151
            }
152
153
            try {
154
                $resourceClassIri = $this->iriConverter->getIriFromResourceClass($resourceClass);
155
            } catch (InvalidArgumentException $e) {
156
                $resourceClassIri = '/nopaths';
157
            }
158
            $resourceClassIri .= '/{id}';
159
160
            $itemOperationsDocs[$resourceClassIri] = $itemOperations['operation'];
161
            $classes[] = $class;
162
        }
163
164
        $doc['swagger'] = self::SWAGGER_VERSION;
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...
165
        if ('' !== $this->title) {
166
            $doc['info']['title'] = $this->title;
167
        }
168
169
        if ('' !== $this->description) {
170
            $doc['info']['description'] = $this->description;
171
        }
172
        $doc['info']['version'] = $this->version ?? '0.0.0';
173
        $doc['host'] = $this->host;
174
        $doc['basePath'] = $this->urlGenerator->generate('api_jsonld_entrypoint');
175
        $doc['definitions'] = $properties;
176
        $doc['externalDocs'] = ['description' => 'Find more about API Platform', 'url' => 'https://api-platform.com'];        $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/ld+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
            break;
274
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 (null !== $className) {
327
                    $reflection = new \ReflectionClass($className);
328
                    if ($reflection->implementsInterface(\DateTimeInterface::class)) {
329
                        return 'string';
330
                    }
331
332
                    $className = $type->getClassName();
333
                    if ($this->resourceClassResolver->isResourceClass($className)) {
334
                        return ['$ref' => sprintf('#/definitions/%s', $this->resourceMetadataFactory->create($className)->getShortName())];
335
                    }
336
                }
337
            break;
338
            default:
339
                return 'null';
340
            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...
341
        }
342
    }
343
}
344