Completed
Pull Request — master (#394)
by
unknown
29:51 queued 19:10
created

Generator   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 301
Duplicated Lines 14.62 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 8
dl 44
loc 301
rs 9.44
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getUri() 0 4 1
A getMethods() 0 4 1
A processRoute() 0 34 1
B getBodyParametersFromDocBlock() 14 32 7
B getQueryParametersFromDocBlock() 14 35 8
A getAuthStatusFromDocBlock() 0 9 2
A parseDocBlock() 0 11 1
B getRouteGroup() 16 25 7
A normalizeParameterType() 0 10 2
A generateDummyValue() 0 31 1
A parseDescription() 0 12 2
A castToType() 0 21 4

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace Mpociot\ApiDoc\Tools;
4
5
use Faker\Factory;
6
use ReflectionClass;
7
use ReflectionMethod;
8
use Illuminate\Routing\Route;
9
use Mpociot\Reflection\DocBlock;
10
use Mpociot\Reflection\DocBlock\Tag;
11
12
class Generator
13
{
14
    /**
15
     * @param Route $route
16
     *
17
     * @return mixed
18
     */
19
    public function getUri(Route $route)
20
    {
21
        return $route->uri();
22
    }
23
24
    /**
25
     * @param Route $route
26
     *
27
     * @return mixed
28
     */
29
    public function getMethods(Route $route)
30
    {
31
        return array_diff($route->methods(), ['HEAD']);
32
    }
33
34
    /**
35
     * @param  \Illuminate\Routing\Route $route
36
     * @param array $apply Rules to apply when generating documentation for this route
0 ignored issues
show
Bug introduced by
There is no parameter named $apply. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
37
     *
38
     * @return array
39
     */
40
    public function processRoute(Route $route, array $rulesToApply = [])
41
    {
42
        $routeAction = $route->getAction();
43
        list($class, $method) = explode('@', $routeAction['uses']);
44
        $controller = new ReflectionClass($class);
45
        $method = $controller->getMethod($method);
46
47
        $routeGroup = $this->getRouteGroup($controller, $method);
48
        $docBlock = $this->parseDocBlock($method);
49
        $bodyParameters = $this->getBodyParametersFromDocBlock($docBlock['tags']);
50
        $queryParameters = $this->getQueryParametersFromDocBlock($docBlock['tags']);
51
        $content = ResponseResolver::getResponse($route, $docBlock['tags'], [
52
            'rules' => $rulesToApply,
53
            'body' => $bodyParameters,
54
            'query' => $queryParameters,
55
        ]);
56
57
        $parsedRoute = [
58
            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
59
            'group' => $routeGroup,
60
            'title' => $docBlock['short'],
61
            'description' => $docBlock['long'],
62
            'methods' => $this->getMethods($route),
63
            'uri' => $this->getUri($route),
64
            'bodyParameters' => $bodyParameters,
65
            'queryParameters' => $queryParameters,
66
            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
67
            'response' => $content,
68
            'showresponse' => ! empty($content),
69
        ];
70
        $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
71
72
        return $parsedRoute;
73
    }
74
75
    /**
76
     * @param array $tags
77
     *
78
     * @return array
79
     */
80
    protected function getBodyParametersFromDocBlock(array $tags)
81
    {
82
        $parameters = collect($tags)
83
            ->filter(function ($tag) {
84
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
85
            })
86
            ->mapWithKeys(function ($tag) {
87
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
88 View Code Duplication
                if (empty($content)) {
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...
89
                    // this means only name and type were supplied
90
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
91
                    $required = false;
92
                    $description = '';
93
                } else {
94
                    list($_, $name, $type, $required, $description) = $content;
0 ignored issues
show
Unused Code introduced by
The assignment to $_ is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
95
                    $description = trim($description);
96
                    if ($description == 'required' && empty(trim($required))) {
97
                        $required = $description;
98
                        $description = '';
99
                    }
100
                    $required = trim($required) == 'required' ? true : false;
101
                }
102
103
                $type = $this->normalizeParameterType($type);
104
                list($description, $example) = $this->parseDescription($description, $type);
105
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;
106
107
                return [$name => compact('type', 'description', 'required', 'value')];
108
            })->toArray();
109
110
        return $parameters;
111
    }
112
113
    /**
114
     * @param array $tags
115
     *
116
     * @return array
117
     */
118
    protected function getQueryParametersFromDocBlock(array $tags)
119
    {
120
        $parameters = collect($tags)
121
            ->filter(function ($tag) {
122
                return $tag instanceof Tag && $tag->getName() === 'queryParam';
123
            })
124
            ->mapWithKeys(function ($tag) {
125
                preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
126 View Code Duplication
                if (empty($content)) {
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...
127
                    // this means only name was supplied
128
                    list($name) = preg_split('/\s+/', $tag->getContent());
129
                    $required = false;
130
                    $description = '';
131
                } else {
132
                    list($_, $name, $required, $description) = $content;
0 ignored issues
show
Unused Code introduced by
The assignment to $_ is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
133
                    $description = trim($description);
134
                    if ($description == 'required' && empty(trim($required))) {
135
                        $required = $description;
136
                        $description = '';
137
                    }
138
                    $required = trim($required) == 'required' ? true : false;
139
                }
140
141
                list($description, $value) = $this->parseDescription($description, 'string');
142
                if (is_null($value)) {
143
                    $value = str_contains($description, ['number', 'count', 'page'])
144
                        ? $this->generateDummyValue('integer')
145
                        : $this->generateDummyValue('string');
146
                }
147
148
                return [$name => compact('description', 'required', 'value')];
149
            })->toArray();
150
151
        return $parameters;
152
    }
153
154
    /**
155
     * @param array $tags
156
     *
157
     * @return bool
158
     */
159
    protected function getAuthStatusFromDocBlock(array $tags)
160
    {
161
        $authTag = collect($tags)
162
            ->first(function ($tag) {
163
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
164
            });
165
166
        return (bool) $authTag;
167
    }
168
169
    /**
170
     * @param ReflectionMethod $method
171
     *
172
     * @return array
173
     */
174
    protected function parseDocBlock(ReflectionMethod $method)
175
    {
176
        $comment = $method->getDocComment();
177
        $phpdoc = new DocBlock($comment);
178
179
        return [
180
            'short' => $phpdoc->getShortDescription(),
181
            'long' => $phpdoc->getLongDescription()->getContents(),
182
            'tags' => $phpdoc->getTags(),
183
        ];
184
    }
185
186
    /**
187
     * @param ReflectionClass $controller
188
     * @param ReflectionMethod $method
189
     *
190
     * @return string
191
     */
192
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
193
    {
194
        // @group tag on the method overrides that on the controller
195
        $docBlockComment = $method->getDocComment();
196 View Code Duplication
        if ($docBlockComment) {
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
            $phpdoc = new DocBlock($docBlockComment);
198
            foreach ($phpdoc->getTags() as $tag) {
199
                if ($tag->getName() === 'group') {
200
                    return $tag->getContent();
201
                }
202
            }
203
        }
204
205
        $docBlockComment = $controller->getDocComment();
206 View Code Duplication
        if ($docBlockComment) {
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...
207
            $phpdoc = new DocBlock($docBlockComment);
208
            foreach ($phpdoc->getTags() as $tag) {
209
                if ($tag->getName() === 'group') {
210
                    return $tag->getContent();
211
                }
212
            }
213
        }
214
215
        return 'general';
216
    }
217
218
    private function normalizeParameterType($type)
219
    {
220
        $typeMap = [
221
            'int' => 'integer',
222
            'bool' => 'boolean',
223
            'double' => 'float',
224
        ];
225
226
        return $type ? ($typeMap[$type] ?? $type) : 'string';
227
    }
228
229
    private function generateDummyValue(string $type)
230
    {
231
        $faker = Factory::create();
232
        $fakes = [
233
            'integer' => function () {
234
                return rand(1, 20);
235
            },
236
            'number' => function () use ($faker) {
237
                return $faker->randomFloat();
238
            },
239
            'float' => function () use ($faker) {
240
                return $faker->randomFloat();
241
            },
242
            'boolean' => function () use ($faker) {
243
                return $faker->boolean();
244
            },
245
            'string' => function () use ($faker) {
246
                return str_random();
247
            },
248
            'array' => function () {
249
                return '[]';
250
            },
251
            'object' => function () {
252
                return '{}';
253
            },
254
        ];
255
256
        $fake = $fakes[$type] ?? $fakes['string'];
257
258
        return $fake();
259
    }
260
261
    /**
262
     * Allows users to specify an example for the parameter by writing 'Example: the-example',
263
     * to be used in example requests and response calls.
264
     *
265
     * @param string $description
266
     * @param string $type The type of the parameter. Used to cast the example provided, if any.
267
     *
268
     * @return array The description and included example.
269
     */
270
    private function parseDescription(string $description, string $type)
271
    {
272
        $example = null;
273
        if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
274
            $description = $content[1];
275
276
            // examples are parsed as strings by default, we need to cast them properly
277
            $example = $this->castToType($content[2], $type);
278
        }
279
280
        return [$description, $example];
281
    }
282
283
    /**
284
     * Cast a value from a string to a specified type.
285
     *
286
     * @param string $value
287
     * @param string $type
288
     *
289
     * @return mixed
290
     */
291
    private function castToType(string $value, string $type)
292
    {
293
        $casts = [
294
            'integer' => 'intval',
295
            'number' => 'floatval',
296
            'float' => 'floatval',
297
            'boolean' => 'boolval',
298
        ];
299
300
        // First, we handle booleans. We can't use a regular cast,
301
        //because PHP considers string 'false' as true.
302
        if ($value == 'false' && $type == 'boolean') {
303
            return false;
304
        }
305
306
        if (isset($casts[$type])) {
307
            return $casts[$type]($value);
308
        }
309
310
        return $value;
311
    }
312
}
313