Completed
Pull Request — master (#460)
by
unknown
01:34
created

Generator::getUri()   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
     * @param Route $route
19
     *
20
     * @return mixed
21
     */
22
    public function getUri(Route $route)
23
    {
24
        return $route->uri();
25
    }
26
27
    /**
28
     * @param Route $route
29
     *
30
     * @return mixed
31
     */
32
    public function getMethods(Route $route)
33
    {
34
        return array_diff($route->methods(), ['HEAD']);
35
    }
36
37
    /**
38
     * @param  \Illuminate\Routing\Route $route
39
     * @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...
40
     *
41
     * @return array
42
     */
43
    public function processRoute(Route $route, array $rulesToApply = [])
44
    {
45
        $routeAction = $route->getAction();
46
        list($class, $method) = explode('@', $routeAction['uses']);
47
        $controller = new ReflectionClass($class);
48
        $method = $controller->getMethod($method);
49
50
        $routeGroup = $this->getRouteGroup($controller, $method);
51
        $docBlock = $this->parseDocBlock($method);
52
        $bodyParameters = $this->getBodyParameters($method, $docBlock['tags']);
53
        $queryParameters = $this->getQueryParametersFromDocBlock($docBlock['tags']);
54
        $content = ResponseResolver::getResponse($route, $docBlock['tags'], [
55
            'rules' => $rulesToApply,
56
            'body' => $bodyParameters,
57
            'query' => $queryParameters,
58
        ]);
59
60
        $parsedRoute = [
61
            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
62
            'group' => $routeGroup,
63
            'title' => $docBlock['short'],
64
            'description' => $docBlock['long'],
65
            'methods' => $this->getMethods($route),
66
            'uri' => $this->getUri($route),
67
            'bodyParameters' => $bodyParameters,
68
            'cleanBodyParameters' => $this->cleanParams($bodyParameters),
69
            'queryParameters' => $queryParameters,
70
            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
71
            'response' => $content,
72
            'showresponse' => ! empty($content),
73
        ];
74
        $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
75
76
        return $parsedRoute;
77
    }
78
79
    protected function getBodyParameters(ReflectionMethod $method, array $tags)
80
    {
81
        foreach ($method->getParameters() as $param) {
82
            $paramType = $param->getType();
83
            if ($paramType === null) {
84
                continue;
85
            }
86
87
            $formRequestClass = new ReflectionClass($paramType->getName());
88
            if ($formRequestClass->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class)) {
89
                $formRequestDocBlock = new DocBlock($formRequestClass->getDocComment());
90
                $bodyParametersFromDocBlock = $this->getBodyParametersFromDocBlock($formRequestDocBlock->getTags());
91
92
                if (count($bodyParametersFromDocBlock)) {
93
                    return $bodyParametersFromDocBlock;
94
                }
95
            }
96
        }
97
98
        return $this->getBodyParametersFromDocBlock($tags);
99
    }
100
101
    /**
102
     * @param array $tags
103
     *
104
     * @return array
105
     */
106
    protected function getBodyParametersFromDocBlock(array $tags)
107
    {
108
        $parameters = collect($tags)
109
            ->filter(function ($tag) {
110
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
111
            })
112
            ->mapWithKeys(function ($tag) {
113
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
114 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...
115
                    // this means only name and type were supplied
116
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
117
                    $required = false;
118
                    $description = '';
119
                } else {
120
                    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...
121
                    $description = trim($description);
122
                    if ($description == 'required' && empty(trim($required))) {
123
                        $required = $description;
124
                        $description = '';
125
                    }
126
                    $required = trim($required) == 'required' ? true : false;
127
                }
128
129
                $type = $this->normalizeParameterType($type);
130
                list($description, $example) = $this->parseDescription($description, $type);
131
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;
132
133
                return [$name => compact('type', 'description', 'required', 'value')];
134
            })->toArray();
135
136
        return $parameters;
137
    }
138
139
    /**
140
     * @param array $tags
141
     *
142
     * @return array
143
     */
144
    protected function getQueryParametersFromDocBlock(array $tags)
145
    {
146
        $parameters = collect($tags)
147
            ->filter(function ($tag) {
148
                return $tag instanceof Tag && $tag->getName() === 'queryParam';
149
            })
150
            ->mapWithKeys(function ($tag) {
151
                preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
152 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...
153
                    // this means only name was supplied
154
                    list($name) = preg_split('/\s+/', $tag->getContent());
155
                    $required = false;
156
                    $description = '';
157
                } else {
158
                    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...
159
                    $description = trim($description);
160
                    if ($description == 'required' && empty(trim($required))) {
161
                        $required = $description;
162
                        $description = '';
163
                    }
164
                    $required = trim($required) == 'required' ? true : false;
165
                }
166
167
                list($description, $value) = $this->parseDescription($description, 'string');
168
                if (is_null($value)) {
169
                    $value = str_contains($description, ['number', 'count', 'page'])
170
                        ? $this->generateDummyValue('integer')
171
                        : $this->generateDummyValue('string');
172
                }
173
174
                return [$name => compact('description', 'required', 'value')];
175
            })->toArray();
176
177
        return $parameters;
178
    }
179
180
    /**
181
     * @param array $tags
182
     *
183
     * @return bool
184
     */
185
    protected function getAuthStatusFromDocBlock(array $tags)
186
    {
187
        $authTag = collect($tags)
188
            ->first(function ($tag) {
189
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
190
            });
191
192
        return (bool) $authTag;
193
    }
194
195
    /**
196
     * @param ReflectionMethod $method
197
     *
198
     * @return array
199
     */
200
    protected function parseDocBlock(ReflectionMethod $method)
201
    {
202
        $comment = $method->getDocComment();
203
        $phpdoc = new DocBlock($comment);
204
205
        return [
206
            'short' => $phpdoc->getShortDescription(),
207
            'long' => $phpdoc->getLongDescription()->getContents(),
208
            'tags' => $phpdoc->getTags(),
209
        ];
210
    }
211
212
    /**
213
     * @param ReflectionClass $controller
214
     * @param ReflectionMethod $method
215
     *
216
     * @return string
217
     */
218
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
219
    {
220
        // @group tag on the method overrides that on the controller
221
        $docBlockComment = $method->getDocComment();
222 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...
223
            $phpdoc = new DocBlock($docBlockComment);
224
            foreach ($phpdoc->getTags() as $tag) {
225
                if ($tag->getName() === 'group') {
226
                    return $tag->getContent();
227
                }
228
            }
229
        }
230
231
        $docBlockComment = $controller->getDocComment();
232 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...
233
            $phpdoc = new DocBlock($docBlockComment);
234
            foreach ($phpdoc->getTags() as $tag) {
235
                if ($tag->getName() === 'group') {
236
                    return $tag->getContent();
237
                }
238
            }
239
        }
240
241
        return 'general';
242
    }
243
244
    private function normalizeParameterType($type)
245
    {
246
        $typeMap = [
247
            'int' => 'integer',
248
            'bool' => 'boolean',
249
            'double' => 'float',
250
        ];
251
252
        return $type ? ($typeMap[$type] ?? $type) : 'string';
253
    }
254
255
    private function generateDummyValue(string $type)
256
    {
257
        $faker = Factory::create();
258
        $fakes = [
259
            'integer' => function () {
260
                return rand(1, 20);
261
            },
262
            'number' => function () use ($faker) {
263
                return $faker->randomFloat();
264
            },
265
            'float' => function () use ($faker) {
266
                return $faker->randomFloat();
267
            },
268
            'boolean' => function () use ($faker) {
269
                return $faker->boolean();
270
            },
271
            'string' => function () use ($faker) {
272
                return str_random();
273
            },
274
            'array' => function () {
275
                return [];
276
            },
277
            'object' => function () {
278
                return new \stdClass;
279
            },
280
        ];
281
282
        $fake = $fakes[$type] ?? $fakes['string'];
283
284
        return $fake();
285
    }
286
287
    /**
288
     * Allows users to specify an example for the parameter by writing 'Example: the-example',
289
     * to be used in example requests and response calls.
290
     *
291
     * @param string $description
292
     * @param string $type The type of the parameter. Used to cast the example provided, if any.
293
     *
294
     * @return array The description and included example.
295
     */
296
    private function parseDescription(string $description, string $type)
297
    {
298
        $example = null;
299
        if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
300
            $description = $content[1];
301
302
            // examples are parsed as strings by default, we need to cast them properly
303
            $example = $this->castToType($content[2], $type);
304
        }
305
306
        return [$description, $example];
307
    }
308
309
    /**
310
     * Cast a value from a string to a specified type.
311
     *
312
     * @param string $value
313
     * @param string $type
314
     *
315
     * @return mixed
316
     */
317
    private function castToType(string $value, string $type)
318
    {
319
        $casts = [
320
            'integer' => 'intval',
321
            'number' => 'floatval',
322
            'float' => 'floatval',
323
            'boolean' => 'boolval',
324
        ];
325
326
        // First, we handle booleans. We can't use a regular cast,
327
        //because PHP considers string 'false' as true.
328
        if ($value == 'false' && $type == 'boolean') {
329
            return false;
330
        }
331
332
        if (isset($casts[$type])) {
333
            return $casts[$type]($value);
334
        }
335
336
        return $value;
337
    }
338
}
339