Completed
Pull Request — master (#591)
by Amrouche
12:54 queued 07:22
created

ApiDocumentationBuilder::getApiDocumentation()   F

Complexity

Conditions 16
Paths 772

Size

Total Lines 93
Code Lines 56

Duplication

Lines 8
Ratio 8.6 %

Importance

Changes 0
Metric Value
dl 8
loc 93
rs 2.3966
c 0
b 0
f 0
cc 16
eloc 56
nc 772
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\JsonLd\ContextBuilderInterface;
19
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
21
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
22
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
23
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
24
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
25
use ApiPlatform\Core\Util\ApiDocumentationBuilderInterface;
26
use Symfony\Component\PropertyInfo\Type;
27
28
/**
29
 * Creates a machine readable Swagger API documentation.
30
 *
31
 * @author Kévin Dunglas <[email protected]>
32
 */
33
final class ApiDocumentationBuilder implements ApiDocumentationBuilderInterface
34
{
35
    private $resourceNameCollectionFactory;
36
    private $resourceMetadataFactory;
37
    private $propertyNameCollectionFactory;
38
    private $propertyMetadataFactory;
39
    private $contextBuilder;
40
    private $resourceClassResolver;
41
    private $operationMethodResolver;
42
    private $urlGenerator;
43
    private $title;
44
    private $description;
45
    private $iriConverter;
46
47 View Code Duplication
    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 = '')
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...
48
    {
49
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
50
        $this->resourceMetadataFactory = $resourceMetadataFactory;
51
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
52
        $this->propertyMetadataFactory = $propertyMetadataFactory;
53
        $this->contextBuilder = $contextBuilder;
54
        $this->resourceClassResolver = $resourceClassResolver;
55
        $this->operationMethodResolver = $operationMethodResolver;
56
        $this->urlGenerator = $urlGenerator;
57
        $this->title = $title;
58
        $this->description = $description;
59
        $this->iriConverter = $iriConverter;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function getApiDocumentation()
66
    {
67
        $classes = [];
68
        $itemOperations = [];
69
        $itemOperationsDocs = [];
70
        $properties = [];
71
72
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
73
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
74
75
            $shortName = $resourceMetadata->getShortName();
76
            $prefixedShortName = ($iri = $resourceMetadata->getIri()) ? $iri : '#'.$shortName;
77
78
            $class = [
79
                'name' => $shortName,
80
                'externalDocs' => [
81
                    'url' => $prefixedShortName,
82
                ],
83
            ];
84
85
            if ($description = $resourceMetadata->getDescription()) {
86
                $class = [
87
                    'name' => $shortName,
88
                    'description' => $description,
89
                    'externalDocs' => [
90
                        'url' => $prefixedShortName,
91
                    ],
92
                ];
93
            }
94
95
            $attributes = $resourceMetadata->getAttributes();
96
            $context = [];
97
98
            if (isset($attributes['normalization_context']['groups'])) {
99
                $context['serializer_groups'] = $attributes['normalization_context']['groups'];
100
            }
101
102 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...
103
                $context['serializer_groups'] = isset($context['serializer_groups']) ? array_merge($context['serializer_groups'], $attributes['denormalization_context']['groups']) : $context['serializer_groups'];
104
            }
105
106
            foreach ($this->propertyNameCollectionFactory->create($resourceClass, $context) as $propertyName) {
107
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
108
109
                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...
110
                    continue;
111
                }
112
113
                $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...
114
                    'type' => $this->getRange($propertyMetadata),
115
                ];
116
117
                $required = [];
118
119
                if ($propertyMetadata->isRequired()) {
120
                    $required = array_merge($required, [$propertyName]);
121
                }
122
123
                if (0 !== count($required)) {
124
                    $properties[$shortName]['required'] = $required;
125
                }
126
127
                $properties[$shortName]['type'] = 'object';
128
                $properties[$shortName]['properties'] = $property;
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 View Code Duplication
            if ($operations = $resourceMetadata->getItemOperations()) {
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...
132
                foreach ($operations as $operationName => $itemOperation) {
133
                    $itemOperations = array_merge($itemOperations, $this->getSwaggerOperation($resourceClass, $resourceMetadata, $operationName, $itemOperation, $prefixedShortName, false));
134
                }
135
            }
136
            $itemOperationsDocs[$this->iriConverter->getIriFromResourceClass($resourceClass)] = $itemOperations;
137
            $classes[] = $class;
138
        }
139
140
        $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...
141
        if ('' !== $this->title) {
142
            $doc['info']['title'] = $this->title;
143
        }
144
145
        if ('' !== $this->description) {
146
            $doc['info']['description'] = $this->description;
147
        }
148
        $doc['host'] = $this->urlGenerator->generate('api_jsonld_entrypoint');
149
        $doc['basePath'] = $this->urlGenerator->generate('api_jsonld_entrypoint');
150
        $doc['definitions'] = $properties;
151
        $doc['externalDocs'] = ['description' => 'Find more about api-platform', 'url' => 'docs'];
152
        $doc['tags'] = $classes;
153
        $doc['schemes'] = ['http']; // more schema ?
154
        $doc['paths'] = $itemOperationsDocs;
155
156
        return $doc;
157
    }
158
159
    /**
160
     * Gets and populates if applicable a Swagger operation.
161
     */
162
    private function getSwaggerOperation(string $resourceClass, ResourceMetadata $resourceMetadata, string $operationName, array $operation, string $prefixedShortName, bool $collection) : array
163
    {
164 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...
165
            $method = $this->operationMethodResolver->getCollectionOperationMethod($resourceClass, $operationName);
166
        } else {
167
            $method = $this->operationMethodResolver->getItemOperationMethod($resourceClass, $operationName);
168
        }
169
170
        $methodSwagger = strtolower($method);
171
        $swaggerOperation = $operation['swagger_context'] ?? [];
172
        $shortName = $resourceMetadata->getShortName();
173
        $swaggerOperation[$methodSwagger] = [];
174
        $swaggerOperation[$methodSwagger]['tags'] = [$shortName];
175
        $swaggerOperation[$methodSwagger]['produces'] = ['application/json'];
176
        $swaggerOperation[$methodSwagger]['consumes'] = $swaggerOperation[$methodSwagger]['produces'];
177
        switch ($method) {
178
            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...
179
                if ($collection) {
180 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...
181
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves the collection of %s resources.', $shortName);
182
                    }
183
                } else {
184 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...
185
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves %s resource.', $shortName);
186
                    }
187
                    $swaggerOperation[$methodSwagger]['parameters'] = [
188
                        'name' => 'id',
189
                        'in' => 'path',
190
                        'required' => true,
191
                        'type' => 'integer',
192
                    ];
193
                }
194
            break;
195
196
            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...
197 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...
198
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Creates a %s resource.', $shortName);
199
                }
200
                $swaggerOperation[$methodSwagger]['parameters'] = [
201
                    'in' => 'body',
202
                    'name' => 'body',
203
                    'description' => sprintf('%s resource to be added', $shortName),
204
                    'schema' => [
205
                        '$ref' => sprintf('%/definitions/%s', $shortName),
206
                    ],
207
                ];
208
                    $swaggerOperation[$methodSwagger]['responses'] = [
209
                        '400' => 'Valid ID',
210
                    ];
211
212
            break;
213
214
            case 'PUT':
215 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...
216
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Replaces the %s resource.', $shortName);
217
                }
218
                break;
219
        }
220
221 View Code Duplication
        if (!isset($swaggerOperation[$methodSwagger]['returns']) &&
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...
222
            (
223
                ('GET' === $method && !$collection) ||
224
                'POST' === $method ||
225
                'PUT' === $method
226
            )
227
        ) {
228
            $swaggerOperation[$methodSwagger]['returns'] = $prefixedShortName;
229
        }
230
231
        if (!isset($swaggerOperation[$methodSwagger]['expects']) &&
232
            ('POST' === $method || 'PUT' === $method)) {
233
            $swaggerOperation[$methodSwagger]['expects'] = $prefixedShortName;
234
        }
235
236
        ksort($swaggerOperation);
237
238
        return $swaggerOperation;
239
    }
240
241
    /**
242
     * Gets the range of the property.
243
     *
244
     * @param PropertyMetadata $propertyMetadata
245
     *
246
     * @return string|null
247
     */
248 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...
249
    {
250
        $type = $propertyMetadata->getType();
251
        if (!$type) {
252
            return;
253
        }
254
255
        if ($type->isCollection() && $collectionType = $type->getCollectionValueType()) {
256
            $type = $collectionType;
257
        }
258
259
        switch ($type->getBuiltinType()) {
260
            case Type::BUILTIN_TYPE_STRING:
261
                return 'string';
262
263
            case Type::BUILTIN_TYPE_INT:
264
                return 'integer';
265
266
            case Type::BUILTIN_TYPE_FLOAT:
267
                return 'number';
268
269
            case Type::BUILTIN_TYPE_BOOL:
270
                return 'boolean';
271
272
            case Type::BUILTIN_TYPE_OBJECT:
273
                $className = $type->getClassName();
274
275
                if ($className) {
276
                    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...
277
                        return 'string';
278
                    }
279
280
                    $className = $type->getClassName();
281
                    if ($this->resourceClassResolver->isResourceClass($className)) {
282
                        return ['$ref' => sprintf('#/definitions/%s', $this->resourceMetadataFactory->create($className)->getShortName())];
283
                    }
284
                }
285
            break;
286
            default:
287
                return 'null';
288
            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...
289
        }
290
    }
291
}
292