Completed
Pull Request — master (#617)
by Amrouche
03:52
created

ApiDocumentationBuilder   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 384
Duplicated Lines 14.84 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 56
lcom 1
cbo 10
dl 57
loc 384
rs 6.5957
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 3
F getApiDocumentation() 45 151 28
C getSwaggerOperation() 12 131 12
C getRange() 0 48 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\Documentation\ApiDocumentationBuilderInterface;
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 Symfony\Component\PropertyInfo\Type;
27
28
/**
29
 * Creates a machine readable Swagger API documentation.
30
 *
31
 * @author Amrouche Hamza <[email protected]>
32
 * @author Kévin Dunglas <[email protected]>
33
 */
34
final class ApiDocumentationBuilder implements ApiDocumentationBuilderInterface
35
{
36
    const SWAGGER_VERSION = '2.0';
37
38
    private $resourceNameCollectionFactory;
39
    private $resourceMetadataFactory;
40
    private $propertyNameCollectionFactory;
41
    private $propertyMetadataFactory;
42
    private $contextBuilder;
43
    private $resourceClassResolver;
44
    private $operationMethodResolver;
45
    private $title;
46
    private $description;
47
    private $iriConverter;
48
    private $version;
49
    private $mimeTypes = [];
50
51
    public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ContextBuilderInterface $contextBuilder, ResourceClassResolverInterface $resourceClassResolver, OperationMethodResolverInterface $operationMethodResolver, IriConverterInterface $iriConverter, array $formats, string $title, string $description, string $version = null)
52
    {
53
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
54
        $this->resourceMetadataFactory = $resourceMetadataFactory;
55
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
56
        $this->propertyMetadataFactory = $propertyMetadataFactory;
57
        $this->contextBuilder = $contextBuilder;
58
        $this->resourceClassResolver = $resourceClassResolver;
59
        $this->operationMethodResolver = $operationMethodResolver;
60
        $this->title = $title;
61
        $this->description = $description;
62
        $this->iriConverter = $iriConverter;
63
        $this->version = $version;
64
65
        foreach ($formats as $format => $mimeTypes) {
66
            foreach ($mimeTypes as $mimeType) {
67
                $this->mimeTypes[] = $mimeType;
68
            }
69
        }
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function getApiDocumentation() : array
76
    {
77
        $classes = [];
78
        $operation = [];
79
        $customOperation = [];
80
81
82
        $itemOperationsDocs = [];
83
        $definitions = [];
84
85
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
86
            $operation['item'] = [];
87
            $operation['collection'] = [];
88
            $customOperations['item'] = [];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$customOperations was never initialized. Although not strictly required by PHP, it is generally a good practice to add $customOperations = 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...
89
            $customOperations['collection'] = [];
0 ignored issues
show
Bug introduced by
The variable $customOperations 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...
90
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
91
92
            $shortName = $resourceMetadata->getShortName();
93
            $prefixedShortName = ($iri = $resourceMetadata->getIri()) ? $iri : '#'.$shortName;
94
95
            $class = [
96
                'name' => $shortName,
97
                'externalDocs' => ['url' => $prefixedShortName],
98
            ];
99
100
            if ($description = $resourceMetadata->getDescription()) {
101
                $class = [
102
                    'name' => $shortName,
103
                    'description' => $description,
104
                    'externalDocs' => ['url' => $prefixedShortName],
105
                ];
106
            }
107
108
            $attributes = $resourceMetadata->getAttributes();
109
            $context = [];
110
111
            if (isset($attributes['normalization_context']['groups'])) {
112
                $context['serializer_groups'] = $attributes['normalization_context']['groups'];
113
            }
114
115 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...
116
                $context['serializer_groups'] = isset($context['serializer_groups']) ? array_merge($context['serializer_groups'], $attributes['denormalization_context']['groups']) : $context['serializer_groups'];
117
            }
118
119
            $definitions[$shortName] = [
120
                'type' => 'object',
121
                'xml' => ['name' => 'response'],
122
            ];
123
124
            foreach ($this->propertyNameCollectionFactory->create($resourceClass, $context) as $propertyName) {
125
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
126
127
                if ($propertyMetadata->isRequired()) {
128
                    $definitions[$shortName]['required'][] = $propertyName;
129
                }
130
131
                $range = $this->getRange($propertyMetadata);
132
                if (empty($range)) {
133
                    continue;
134
                }
135
136
                if ($propertyMetadata->getDescription()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyMetadata->getDescription() of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
137
                    $definitions[$shortName]['properties'][$propertyName]['description'] = $propertyMetadata->getDescription();
138
                }
139
140
                if ($range['complex']) {
141
                    $definitions[$shortName]['properties'][$propertyName] = ['$ref' => $range['value']];
142
                } else {
143
                    $definitions[$shortName]['properties'][$propertyName] = ['type' => $range['value']];
144
145
                    if (isset($range['example'])) {
146
                        $definitions[$shortName]['properties'][$propertyName]['example'] = $range['example'];
147
                    }
148
                }
149
            }
150
151 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...
152
                foreach ($operations as $operationName => $itemOperation) {
153
                    $method = $this->operationMethodResolver->getItemOperationMethod($resourceClass, $operationName);
154
                    $swaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $operationName, $itemOperation, $prefixedShortName, false, $definitions, $method);
155
                    $operation['item'] = array_merge($operation['item'], $swaggerOperation);
156
                    if ($operationName !== strtolower($method)) {
157
                        $customOperations['item'][] = $operationName;
158
                    }
159
                }
160
            }
161
162 View Code Duplication
            if ($operations = $resourceMetadata->getCollectionOperations()) {
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...
163
                foreach ($operations as $operationName => $collectionOperation) {
164
                    $method = $this->operationMethodResolver->getCollectionOperationMethod($resourceClass, $operationName);
165
                    $swaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $operationName, $collectionOperation, $prefixedShortName, true, $definitions, $method);
166
                    $operation['collection'] = array_merge($operation['collection'], $swaggerOperation);
167
                    if ($operationName !== strtolower($method)) {
168
                        $customOperations['collection'][] = $operationName;
169
                    }
170
                }
171
            }
172
            try {
173
                $resourceClassIri = $this->iriConverter->getIriFromResourceClass($resourceClass);
174
                $itemOperationsDocs[$resourceClassIri] = $operation['collection'];
175
176 View Code Duplication
                if (!empty($customOperations['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...
177
                    foreach ($customOperations['collection'] as $customOperation) {
178
                        $path = $resourceMetadata->getCollectionOperationAttribute($customOperation, 'path');
179
                        if (null !== $path) {
180
                            $method = $this->operationMethodResolver->getCollectionOperationMethod($resourceClass, $customOperation);
181
                            $customSwaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $customOperation, [$method], $prefixedShortName, true, $definitions, $method);
182
183
                            $itemOperationsDocs[$path] = $customSwaggerOperation;
184
                        }
185
                    }
186
                }
187
188
189
                $resourceClassIri .= '/{id}';
190
191
                $itemOperationsDocs[$resourceClassIri] = $operation['item'];
192
193 View Code Duplication
                if (!empty($customOperations['item'])) {
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...
194
                    foreach ($customOperations['item'] as $customOperation) {
195
                        $path = $resourceMetadata->getItemOperationAttribute($customOperation, 'path');
196
                        if (null !== $path) {
197
                            $method = $this->operationMethodResolver->getItemOperationMethod($resourceClass, $customOperation);
198
                            $customSwaggerOperation = $this->getSwaggerOperation($resourceClass, $resourceMetadata, $customOperation, [$method], $prefixedShortName, true, $definitions, $method);
199
200
                            $itemOperationsDocs[$path] = $customSwaggerOperation;
201
                        }
202
                    }
203
                }
204
            } catch (InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
205
            }
206
207
            $classes[] = $class;
208
        }
209
210
        $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...
211
        if ('' !== $this->title) {
212
            $doc['info']['title'] = $this->title;
213
        }
214
215
        if ('' !== $this->description) {
216
            $doc['info']['description'] = $this->description;
217
        }
218
        $doc['info']['version'] = $this->version ?? '0.0.0';
219
        $doc['definitions'] = $definitions;
220
        $doc['externalDocs'] = ['description' => 'Find more about API Platform', 'url' => 'https://api-platform.com'];
221
        $doc['tags'] = $classes;
222
        $doc['paths'] = $itemOperationsDocs;
223
224
        return $doc;
225
    }
226
227
    /**
228
     * Gets and populates if applicable a Swagger operation.
229
     */
230
    private function getSwaggerOperation(string $resourceClass, ResourceMetadata $resourceMetadata, string $operationName, array $operation, string $prefixedShortName, bool $collection, array $properties, string $method) : array
0 ignored issues
show
Unused Code introduced by
The parameter $operationName 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...
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...
Unused Code introduced by
The parameter $properties 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...
231
    {
232
        $methodSwagger = strtolower($method);
233
        $swaggerOperation = $operation['swagger_context'] ?? [];
234
        $shortName = $resourceMetadata->getShortName();
235
        $swaggerOperation[$methodSwagger] = [];
236
        $swaggerOperation[$methodSwagger]['tags'] = [$shortName];
237
238
        switch ($method) {
239
            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...
240
                $swaggerOperation[$methodSwagger]['produces'] = $this->mimeTypes;
241
242
                if ($collection) {
243 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...
244
                        $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves the collection of %s resources.', $shortName);
245
                    }
246
247
                    $swaggerOperation[$methodSwagger]['responses'] = [
248
                        '200' => [
249
                            'description' => 'Successful operation',
250
                             'schema' => [
251
                                'type' => 'array',
252
                                'items' => ['$ref' => sprintf('#/definitions/%s', $shortName)],
253
                             ],
254
                        ],
255
                    ];
256
                    break;
257
                }
258
259 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...
260
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Retrieves %s resource.', $shortName);
261
                }
262
263
                $swaggerOperation[$methodSwagger]['parameters'][] = [
264
                    'name' => 'id',
265
                    'in' => 'path',
266
                    'required' => true,
267
                    'type' => 'integer',
268
                ];
269
270
                $swaggerOperation[$methodSwagger]['responses'] = [
271
                    '200' => [
272
                        'description' => 'Successful operation',
273
                        'schema' => ['$ref' => sprintf('#/definitions/%s', $shortName)],
274
                    ],
275
                    '404' => ['description' => 'Resource not found'],
276
                ];
277
                break;
278
279
            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...
280
                $swaggerOperation[$methodSwagger]['consumes'] = $swaggerOperation[$methodSwagger]['produces'] = $this->mimeTypes;
281
282 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...
283
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Creates a %s resource.', $shortName);
284
                }
285
286
                if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
287
                    $swaggerOperation[$methodSwagger]['parameters'][] = [
288
                        'in' => 'body',
289
                        'name' => 'body',
290
                        'description' => sprintf('%s resource to be added', $shortName),
291
                        'schema' => [
292
                            '$ref' => sprintf('#/definitions/%s', $shortName),
293
                        ],
294
                    ];
295
                }
296
297
                $swaggerOperation[$methodSwagger]['responses'] = [
298
                        '201' => [
299
                            'description' => 'Successful operation',
300
                            'schema' => ['$ref' => sprintf('#/definitions/%s', $shortName)],
301
                        ],
302
                        '400' => ['description' => 'Invalid input'],
303
                        '404' => ['description' => 'Resource not found'],
304
                ];
305
            break;
306
307
            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...
308
                $swaggerOperation[$methodSwagger]['consumes'] = $swaggerOperation[$methodSwagger]['produces'] = $this->mimeTypes;
309
310 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...
311
                    $swaggerOperation[$methodSwagger]['summary'] = sprintf('Replaces the %s resource.', $shortName);
312
                }
313
314
                if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
315
                    $swaggerOperation[$methodSwagger]['parameters'] = [
316
                        [
317
                            'name' => 'id',
318
                            'in' => 'path',
319
                            'required' => true,
320
                            'type' => 'integer',
321
                        ],
322
                        [
323
                            'in' => 'body',
324
                            'name' => 'body',
325
                            'description' => sprintf('%s resource to be added', $shortName),
326
                            'schema' => [
327
                                '$ref' => sprintf('#/definitions/%s', $shortName),
328
                            ],
329
                        ],
330
                    ];
331
                }
332
333
                $swaggerOperation[$methodSwagger]['responses'] = [
334
                    '200' => [
335
                        'description' => 'Successful operation',
336
                        'schema' => ['$ref' => sprintf('#/definitions/%s', $shortName)],
337
                    ],
338
                    '400' => ['description' => 'Invalid input'],
339
                    '404' => ['description' => 'Resource not found'],
340
                ];
341
            break;
342
343
            case 'DELETE':
344
                $swaggerOperation[$methodSwagger]['responses'] = [
345
                    '204' => ['description' => 'Deleted'],
346
                    '404' => ['description' => 'Resource not found'],
347
                ];
348
349
                $swaggerOperation[$methodSwagger]['parameters'] = [[
350
                    'name' => 'id',
351
                    'in' => 'path',
352
                    'required' => true,
353
                    'type' => 'integer',
354
                ]];
355
            break;
356
        }
357
        ksort($swaggerOperation);
358
359
        return $swaggerOperation;
360
    }
361
362
    /**
363
     * Gets the range of the property.
364
     *
365
     * @param PropertyMetadata $propertyMetadata
366
     *
367
     * @return array|null
368
     */
369
    private function getRange(PropertyMetadata $propertyMetadata) : array
370
    {
371
        $type = $propertyMetadata->getType();
372
        if (!$type) {
373
            return [];
374
        }
375
376
        if ($type->isCollection() && $collectionType = $type->getCollectionValueType()) {
377
            $type = $collectionType;
378
        }
379
380
        switch ($type->getBuiltinType()) {
381
            case Type::BUILTIN_TYPE_STRING:
382
                return ['complex' => false, 'value' => 'string'];
383
384
            case Type::BUILTIN_TYPE_INT:
385
                return ['complex' => false, 'value' => 'integer'];
386
387
            case Type::BUILTIN_TYPE_FLOAT:
388
                return ['complex' => false, 'value' => 'number'];
389
390
            case Type::BUILTIN_TYPE_BOOL:
391
                return ['complex' => false, 'value' => 'boolean'];
392
393
            case Type::BUILTIN_TYPE_OBJECT:
394
                $className = $type->getClassName();
395
                if (null === $className) {
396
                    return [];
397
                }
398
399
                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...
400
                    return ['complex' => false, 'value' => 'string', 'example' => '1988-01-21T00:00:00+00:00'];
401
                }
402
403
                if (!$this->resourceClassResolver->isResourceClass($className)) {
404
                    return [];
405
                }
406
407
                if ($propertyMetadata->isReadableLink()) {
408
                    return ['complex' => true, 'value' => sprintf('#/definitions/%s', $this->resourceMetadataFactory->create($className)->getShortName())];
409
                }
410
411
                return ['complex' => false, 'value' => 'string', 'example' => '/my/iri'];
412
413
            default:
414
                return ['complex' => false, 'value' => 'null'];
415
        }
416
    }
417
}
418