Completed
Pull Request — master (#506)
by Faton
03:04
created

Generator::getMethods()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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
use Mpociot\ApiDoc\Tools\Traits\ParamHelpers;
12
13
class Generator
14
{
15
    use ParamHelpers;
16
17
    /**
18
     * @var string The seed to be used with Faker.
19
     * Useful when you want to always have the same fake output.
20
     */
21
    private $fakerSeed = null;
22
23
    public function __construct(string $fakerSeed = null)
24
    {
25
        $this->fakerSeed = $fakerSeed;
26
    }
27
28
    /**
29
     * @param Route $route
30
     *
31
     * @return mixed
32
     */
33
    public function getUri(Route $route)
34
    {
35
        return $route->uri();
36
    }
37
38
    /**
39
     * @param Route $route
40
     *
41
     * @return mixed
42
     */
43
    public function getMethods(Route $route)
44
    {
45
        return array_diff($route->methods(), ['HEAD']);
46
    }
47
48
    /**
49
     * @param  \Illuminate\Routing\Route $route
50
     * @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...
51
     *
52
     * @return array
53
     */
54
    public function processRoute(Route $route, array $rulesToApply = [])
55
    {
56
        $routeAction = $route->getAction();
57
        list($class, $method) = explode('@', $routeAction['uses']);
58
        $controller = new ReflectionClass($class);
59
        $method = $controller->getMethod($method);
60
61
        $routeGroup = $this->getRouteGroup($controller, $method);
62
        $docBlock = $this->parseDocBlock($method);
63
        $bodyParameters = $this->getBodyParameters($method, $docBlock['tags']);
64
        $queryParameters = $this->getQueryParameters($method, $docBlock['tags']);
65
        $content = ResponseResolver::getResponse($route, $docBlock['tags'], [
66
            'rules' => $rulesToApply,
67
            'body' => $bodyParameters,
68
            'query' => $queryParameters,
69
        ]);
70
71
        $parsedRoute = [
72
            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
73
            'group' => $routeGroup,
74
            'title' => $docBlock['short'],
75
            'description' => $docBlock['long'],
76
            'methods' => $this->getMethods($route),
77
            'uri' => $this->getUri($route),
78
            'boundUri' => Utils::getFullUrl($route, $rulesToApply['bindings'] ?? []),
79
            'queryParameters' => $queryParameters,
80
            'bodyParameters' => $bodyParameters,
81
            'cleanBodyParameters' => $this->cleanParams($bodyParameters),
82
            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
83
            'response' => $content,
84
            'showresponse' => ! empty($content),
85
        ];
86
        $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
87
88
        return $parsedRoute;
89
    }
90
91 View Code Duplication
    protected function getBodyParameters(ReflectionMethod $method, array $tags)
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...
92
    {
93
        foreach ($method->getParameters() as $param) {
94
            $paramType = $param->getType();
95
            if ($paramType === null) {
96
                continue;
97
            }
98
99
            $parameterClassName = version_compare(phpversion(), '7.1.0', '<')
100
                ? $paramType->__toString()
101
                : $paramType->getName();
102
103
            try {
104
                $parameterClass = new ReflectionClass($parameterClassName);
105
            } catch (\ReflectionException $e) {
106
                continue;
107
            }
108
109
            if ( class_exists('\Illuminate\Foundation\Http\FormRequest') && $parameterClass->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class) || class_exists('\Dingo\Api\Http\FormRequest') && $parameterClass->isSubclassOf(\Dingo\Api\Http\FormRequest::class)) {
110
                $formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
111
                $bodyParametersFromDocBlock = $this->getBodyParametersFromDocBlock($formRequestDocBlock->getTags());
112
113
                if (count($bodyParametersFromDocBlock)) {
114
                    return $bodyParametersFromDocBlock;
115
                }
116
            }
117
        }
118
119
        return $this->getBodyParametersFromDocBlock($tags);
120
    }
121
122
    /**
123
     * @param array $tags
124
     *
125
     * @return array
126
     */
127
    protected function getBodyParametersFromDocBlock(array $tags)
128
    {
129
        $parameters = collect($tags)
130
            ->filter(function ($tag) {
131
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
132
            })
133
            ->mapWithKeys(function ($tag) {
134
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
135 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...
136
                    // this means only name and type were supplied
137
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
138
                    $required = false;
139
                    $description = '';
140
                } else {
141
                    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...
142
                    $description = trim($description);
143
                    if ($description == 'required' && empty(trim($required))) {
144
                        $required = $description;
145
                        $description = '';
146
                    }
147
                    $required = trim($required) == 'required' ? true : false;
148
                }
149
150
                $type = $this->normalizeParameterType($type);
151
                list($description, $example) = $this->parseDescription($description, $type);
152
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;
153
154
                return [$name => compact('type', 'description', 'required', 'value')];
155
            })->toArray();
156
157
        return $parameters;
158
    }
159
160
    /**
161
     * @param ReflectionMethod $method
162
     * @param array $tags
163
     *
164
     * @return array
165
     */
166 View Code Duplication
    protected function getQueryParameters(ReflectionMethod $method, array $tags)
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...
167
    {
168
        foreach ($method->getParameters() as $param) {
169
            $paramType = $param->getType();
170
            if ($paramType === null) {
171
                continue;
172
            }
173
174
            $parameterClassName = version_compare(phpversion(), '7.1.0', '<')
175
                ? $paramType->__toString()
176
                : $paramType->getName();
177
178
            try {
179
                $parameterClass = new ReflectionClass($parameterClassName);
180
            } catch (\ReflectionException $e) {
181
                continue;
182
            }
183
184
            if ( class_exists('\Illuminate\Foundation\Http\FormRequest') && $parameterClass->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class) || class_exists('\Dingo\Api\Http\FormRequest') && $parameterClass->isSubclassOf(\Dingo\Api\Http\FormRequest::class)) {
185
                $formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
186
                $queryParametersFromDocBlock = $this->getQueryParametersFromDocBlock($formRequestDocBlock->getTags());
187
188
                if (count($queryParametersFromDocBlock)) {
189
                    return $queryParametersFromDocBlock;
190
                }
191
            }
192
        }
193
194
        return $this->getQueryParametersFromDocBlock($tags);
195
    }
196
197
    /**
198
     * @param array $tags
199
     *
200
     * @return array
201
     */
202
    protected function getQueryParametersFromDocBlock(array $tags)
203
    {
204
        $parameters = collect($tags)
205
            ->filter(function ($tag) {
206
                return $tag instanceof Tag && $tag->getName() === 'queryParam';
207
            })
208
            ->mapWithKeys(function ($tag) {
209
                preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
210 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...
211
                    // this means only name was supplied
212
                    list($name) = preg_split('/\s+/', $tag->getContent());
213
                    $required = false;
214
                    $description = '';
215
                } else {
216
                    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...
217
                    $description = trim($description);
218
                    if ($description == 'required' && empty(trim($required))) {
219
                        $required = $description;
220
                        $description = '';
221
                    }
222
                    $required = trim($required) == 'required' ? true : false;
223
                }
224
225
                list($description, $value) = $this->parseDescription($description, 'string');
226
                if (is_null($value)) {
227
                    $value = str_contains($description, ['number', 'count', 'page'])
228
                        ? $this->generateDummyValue('integer')
229
                        : $this->generateDummyValue('string');
230
                }
231
232
                return [$name => compact('description', 'required', 'value')];
233
            })->toArray();
234
235
        return $parameters;
236
    }
237
238
    /**
239
     * @param array $tags
240
     *
241
     * @return bool
242
     */
243
    protected function getAuthStatusFromDocBlock(array $tags)
244
    {
245
        $authTag = collect($tags)
246
            ->first(function ($tag) {
247
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
248
            });
249
250
        return (bool) $authTag;
251
    }
252
253
    /**
254
     * @param ReflectionMethod $method
255
     *
256
     * @return array
257
     */
258
    protected function parseDocBlock(ReflectionMethod $method)
259
    {
260
        $comment = $method->getDocComment();
261
        $phpdoc = new DocBlock($comment);
262
263
        return [
264
            'short' => $phpdoc->getShortDescription(),
265
            'long' => $phpdoc->getLongDescription()->getContents(),
266
            'tags' => $phpdoc->getTags(),
267
        ];
268
    }
269
270
    /**
271
     * @param ReflectionClass $controller
272
     * @param ReflectionMethod $method
273
     *
274
     * @return string
275
     */
276
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
277
    {
278
        // @group tag on the method overrides that on the controller
279
        $docBlockComment = $method->getDocComment();
280 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...
281
            $phpdoc = new DocBlock($docBlockComment);
282
            foreach ($phpdoc->getTags() as $tag) {
283
                if ($tag->getName() === 'group') {
284
                    return $tag->getContent();
285
                }
286
            }
287
        }
288
289
        $docBlockComment = $controller->getDocComment();
290 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...
291
            $phpdoc = new DocBlock($docBlockComment);
292
            foreach ($phpdoc->getTags() as $tag) {
293
                if ($tag->getName() === 'group') {
294
                    return $tag->getContent();
295
                }
296
            }
297
        }
298
299
        // TODO: get rid of ungrouped_name in next major release
300
        return config('apidoc.default_group', config('apidoc.ungrouped_name', 'general'));
301
    }
302
303
    private function normalizeParameterType($type)
304
    {
305
        $typeMap = [
306
            'int' => 'integer',
307
            'bool' => 'boolean',
308
            'double' => 'float',
309
        ];
310
311
        return $type ? ($typeMap[$type] ?? $type) : 'string';
312
    }
313
314
    private function generateDummyValue(string $type)
315
    {
316
        $faker = Factory::create();
317
        if ($this->fakerSeed) {
318
            $faker->seed($this->fakerSeed);
319
        }
320
        $fakeFactories = [
321
            'integer' => function () use ($faker) {
322
                return $faker->numberBetween(1, 20);
323
            },
324
            'number' => function () use ($faker) {
325
                return $faker->randomFloat();
326
            },
327
            'float' => function () use ($faker) {
328
                return $faker->randomFloat();
329
            },
330
            'boolean' => function () use ($faker) {
331
                return $faker->boolean();
332
            },
333
            'string' => function () use ($faker) {
334
                return $faker->word;
335
            },
336
            'array' => function () {
337
                return [];
338
            },
339
            'object' => function () {
340
                return new \stdClass;
341
            },
342
        ];
343
344
        $fakeFactory = $fakeFactories[$type] ?? $fakeFactories['string'];
345
346
        return $fakeFactory();
347
    }
348
349
    /**
350
     * Allows users to specify an example for the parameter by writing 'Example: the-example',
351
     * to be used in example requests and response calls.
352
     *
353
     * @param string $description
354
     * @param string $type The type of the parameter. Used to cast the example provided, if any.
355
     *
356
     * @return array The description and included example.
357
     */
358
    private function parseDescription(string $description, string $type)
359
    {
360
        $example = null;
361
        if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
362
            $description = $content[1];
363
364
            // examples are parsed as strings by default, we need to cast them properly
365
            $example = $this->castToType($content[2], $type);
366
        }
367
368
        return [$description, $example];
369
    }
370
371
    /**
372
     * Cast a value from a string to a specified type.
373
     *
374
     * @param string $value
375
     * @param string $type
376
     *
377
     * @return mixed
378
     */
379
    private function castToType(string $value, string $type)
380
    {
381
        $casts = [
382
            'integer' => 'intval',
383
            'number' => 'floatval',
384
            'float' => 'floatval',
385
            'boolean' => 'boolval',
386
        ];
387
388
        // First, we handle booleans. We can't use a regular cast,
389
        //because PHP considers string 'false' as true.
390
        if ($value == 'false' && $type == 'boolean') {
391
            return false;
392
        }
393
394
        if (isset($casts[$type])) {
395
            return $casts[$type]($value);
396
        }
397
398
        return $value;
399
    }
400
}
401