Completed
Pull Request — master (#591)
by Amrouche
05:03 queued 01:08
created

ApiDocumentationBuilder   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 262
Duplicated Lines 23.66 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 48
lcom 1
cbo 11
dl 62
loc 262
rs 8.4864
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 14 14 1
F getApiDocumentation() 8 93 16
C getSwaggerOperation() 26 78 18
C getRange() 14 46 13

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ApiDocumentationBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ApiDocumentationBuilder, and based on these observations, apply Extract Interface, too.

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