Completed
Pull Request — master (#591)
by Amrouche
05:32
created

ApiDocumentationBuilder   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 266
Duplicated Lines 34.21 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 14 14 1
F getApiDocumentation() 8 100 17
C getSwaggerOperation() 26 78 18
C getRange() 43 43 12

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