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

ApiDocumentationBuilder::getApiDocumentation()   F

Complexity

Conditions 18
Paths 2564

Size

Total Lines 110
Code Lines 67

Duplication

Lines 3
Ratio 2.73 %

Importance

Changes 0
Metric Value
dl 3
loc 110
rs 2
c 0
b 0
f 0
cc 18
eloc 67
nc 2564
nop 0

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
53
    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)
54
    {
55
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
56
        $this->resourceMetadataFactory = $resourceMetadataFactory;
57
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
58
        $this->propertyMetadataFactory = $propertyMetadataFactory;
59
        $this->contextBuilder = $contextBuilder;
60
        $this->resourceClassResolver = $resourceClassResolver;
61
        $this->operationMethodResolver = $operationMethodResolver;
62
        $this->urlGenerator = $urlGenerator;
63
        $this->title = $title;
64
        $this->description = $description;
65
        $this->iriConverter = $iriConverter;
66
        $this->version = $version;
67
        $this->host = $host;
68
        $this->schema[] = $schema;
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function getApiDocumentation()
75
    {
76
        $classes = [];
77
        $itemOperations = [];
78
        $itemOperations['operation'] = [];
79
80
        $itemOperationsDocs = [];
81
        $properties = [];
82
83
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
84
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
85
86
            $shortName = $resourceMetadata->getShortName();
87
            $prefixedShortName = ($iri = $resourceMetadata->getIri()) ? $iri : '#'.$shortName;
88
89
            $class = [
90
                'name' => $shortName,
91
                'externalDocs' => [
92
                    'url' => $prefixedShortName,
93
                ],
94
            ];
95
96
            if ($description = $resourceMetadata->getDescription()) {
97
                $class = [
98
                    'name' => $shortName,
99
                    'description' => $description,
100
                    'externalDocs' => [
101
                        'url' => $prefixedShortName,
102
                    ],
103
                ];
104
            }
105
106
            $attributes = $resourceMetadata->getAttributes();
107
            $context = [];
108
109
            if (isset($attributes['normalization_context']['groups'])) {
110
                $context['serializer_groups'] = $attributes['normalization_context']['groups'];
111
            }
112
113 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...
114
                $context['serializer_groups'] = isset($context['serializer_groups']) ? array_merge($context['serializer_groups'], $attributes['denormalization_context']['groups']) : $context['serializer_groups'];
115
            }
116
117
            foreach ($this->propertyNameCollectionFactory->create($resourceClass, $context) as $propertyName) {
118
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
119
120
                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...
121
                    continue;
122
                }
123
                $range = $this->getRange($propertyMetadata);
124
125
                $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...
126
                    'type' => $range,
127
                ];
128
129
                if (is_array($range)) {
130
                    $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...
131
                }
132
133
                $required = [];
134
135
                if ($propertyMetadata->isRequired()) {
136
                    $required = array_merge($required, [$propertyName]);
137
                }
138
139
                if (!empty($required)) {
140
                    $properties[$shortName]['required'] = $required;
141
                }
142
143
                $properties[$shortName]['type'] = 'object';
144
                $properties[$shortName]['properties'] = $property;
145
            }
146
147
            if ($operations = $resourceMetadata->getItemOperations()) {
148
                foreach ($operations as $operationName => $itemOperation) {
149
                    $swaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $operationName, $itemOperation, $prefixedShortName, false);
150
                    $itemOperations['operation'] = array_merge($itemOperations['operation'], $swaggerOperation);
151
                }
152
            }
153
154
            try {
155
                $resourceClassIri = $this->iriConverter->getIriFromResourceClass($resourceClass);
156
            } catch (InvalidArgumentException $e) {
157
                $resourceClassIri = '/nopaths';
158
            }
159
            $resourceClassIri .= '/{id}';
160
161
            $itemOperationsDocs[$resourceClassIri] = $itemOperations['operation'];
162
            $classes[] = $class;
163
        }
164
165
        $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...
166
        if ('' !== $this->title) {
167
            $doc['info']['title'] = $this->title;
168
        }
169
170
        if ('' !== $this->description) {
171
            $doc['info']['description'] = $this->description;
172
        }
173
        $doc['info']['version'] = $this->version ?? '0.0.0';
174
        $doc['host'] = $this->host;
175
        $doc['basePath'] = $this->urlGenerator->generate('api_jsonld_entrypoint');
176
        $doc['definitions'] = $properties;
177
        $doc['externalDocs'] = ['description' => 'Find more about API Platform', 'url' => 'https://api-platform.com'];
178
        $doc['tags'] = $classes;
179
        $doc['schemes'] = $this->schema; // more schema ?
180
        $doc['paths'] = $itemOperationsDocs;
181
182
        return $doc;
183
    }
184
185
    /**
186
     * Gets and populates if applicable a Swagger operation.
187
     */
188
    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...
189
    {
190 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...
191
            $method = $this->operationMethodResolver->getCollectionOperationMethod($resourceClass, $operationName);
192
        } else {
193
            $method = $this->operationMethodResolver->getItemOperationMethod($resourceClass, $operationName);
194
        }
195
        $methodSwagger = strtolower($method);
196
        $swaggerOperation = $operation['swagger_context'] ?? [];
197
        $shortName = $resourceMetadata->getShortName();
198
        $swaggerOperation[$methodSwagger] = [];
199
        $swaggerOperation[$methodSwagger]['tags'] = [$shortName];
200
        $swaggerOperation[$methodSwagger]['produces'] = ['application/ld+json'];
201
        $swaggerOperation[$methodSwagger]['consumes'] = $swaggerOperation[$methodSwagger]['produces'];
202
        switch ($method) {
203
            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...
204
                if ($collection) {
205 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...
206
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves the collection of %s resources.', $shortName);
207
                    }
208
                } else {
209 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...
210
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves %s resource.', $shortName);
211
                    }
212
                    $swaggerOperation[$methodSwagger]['parameters'][] = [
213
                        'name' => 'id',
214
                        'in' => 'path',
215
                        'required' => true,
216
                        'type' => 'integer',
217
                    ];
218
                }
219
                $swaggerOperation[$methodSwagger]['responses'] = [
220
                    '200' => ['description' => 'Valid ID'],
221
                ];
222
                break;
223
224
            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...
225 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...
226
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Creates a %s resource.', $shortName);
227
                }
228
                if ($this->resourceClassResolver->isResourceClass($shortName)) {
229
                    $swaggerOperation[$methodSwagger]['parameters'] = [
230
                        'in' => 'body',
231
                        'name' => 'body',
232
                        'description' => sprintf('%s resource to be added', $shortName),
233
                        'schema' => [
234
                            '$ref' => sprintf('#/definitions/%s', $shortName),
235
                        ],
236
                    ];
237
                }
238
239
                $swaggerOperation[$methodSwagger]['responses'] = [
240
                        '201' => ['description' => 'Valid ID'],
241
                    ];
242
243
            break;
244
245
            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...
246 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...
247
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Replaces the %s resource.', $shortName);
248
                }
249
                $swaggerOperation[$methodSwagger]['parameters'] = [[
250
                    'name' => 'id',
251
                    'in' => 'path',
252
                    'required' => true,
253
                    'type' => 'integer',
254
                ]];
255
                if ($this->resourceClassResolver->isResourceClass($shortName)) {
256
                    $swaggerOperation[$methodSwagger]['parameters'] = [[
257
                        'name' => 'id',
258
                        'in' => 'path',
259
                        'required' => true,
260
                        'type' => 'integer',
261
                    ],
262
                        [
263
                        'in' => 'body',
264
                        'name' => 'body',
265
                        'description' => sprintf('%s resource to be added', $shortName),
266
                        'schema' => [
267
                            '$ref' => sprintf('#/definitions/%s', $shortName),
268
                        ],
269
                    ], ];
270
                }
271
272
                $swaggerOperation[$methodSwagger]['responses'] = [
273
                    '200' => ['description' => 'Valid ID'],
274
                ];
275
            break;
276
277
            case 'DELETE':
278
                $swaggerOperation[$methodSwagger]['responses'] = [
279
                    '204' => ['description' => 'Deleted'],
280
                ];
281
                $swaggerOperation[$methodSwagger]['parameters'] = [[
282
                    'name' => 'id',
283
                    'in' => 'path',
284
                    'required' => true,
285
                    'type' => 'integer',
286
                ]];
287
            break;
288
        }
289
        ksort($swaggerOperation);
290
291
        return $swaggerOperation;
292
    }
293
294
    /**
295
     * Gets the range of the property.
296
     *
297
     * @param PropertyMetadata $propertyMetadata
298
     *
299
     * @return string|null
300
     */
301 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...
302
    {
303
        $type = $propertyMetadata->getType();
304
        if (!$type) {
305
            return;
306
        }
307
308
        if ($type->isCollection() && $collectionType = $type->getCollectionValueType()) {
309
            $type = $collectionType;
310
        }
311
312
        switch ($type->getBuiltinType()) {
313
            case Type::BUILTIN_TYPE_STRING:
314
                return 'string';
315
316
            case Type::BUILTIN_TYPE_INT:
317
                return 'integer';
318
319
            case Type::BUILTIN_TYPE_FLOAT:
320
                return 'number';
321
322
            case Type::BUILTIN_TYPE_BOOL:
323
                return 'boolean';
324
325
            case Type::BUILTIN_TYPE_OBJECT:
326
                $className = $type->getClassName();
327
328
                if (null !== $className) {
329
                    $reflection = new \ReflectionClass($className);
330
                    if ($reflection->implementsInterface(\DateTimeInterface::class)) {
331
                        return 'string';
332
                    }
333
334
                    $className = $type->getClassName();
335
                    if ($this->resourceClassResolver->isResourceClass($className)) {
336
                        return ['$ref' => sprintf('#/definitions/%s', $this->resourceMetadataFactory->create($className)->getShortName())];
337
                    }
338
                }
339
            break;
340
            default:
341
                return 'null';
342
            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...
343
        }
344
    }
345
}
346