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

Generator::getAuthStatusFromDocBlock()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
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
            $parameterClassName = version_compare(phpversion(), '7.1.0', '<')
88
                ? $paramType->__toString()
89
                : $paramType->getName();
90
            $parameterClass = new ReflectionClass($parameterClassName);
91
            if ($parameterClass->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class)) {
92
                $formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
93
                $bodyParametersFromDocBlock = $this->getBodyParametersFromDocBlock($formRequestDocBlock->getTags());
94
95
                if (count($bodyParametersFromDocBlock)) {
96
                    return $bodyParametersFromDocBlock;
97
                }
98
            }
99
        }
100
101
        return $this->getBodyParametersFromDocBlock($tags);
102
    }
103
104
    /**
105
     * @param array $tags
106
     *
107
     * @return array
108
     */
109
    protected function getBodyParametersFromDocBlock(array $tags)
110
    {
111
        $parameters = collect($tags)
112
            ->filter(function ($tag) {
113
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
114
            })
115
            ->mapWithKeys(function ($tag) {
116
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
117 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...
118
                    // this means only name and type were supplied
119
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
120
                    $required = false;
121
                    $description = '';
122
                } else {
123
                    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...
124
                    $description = trim($description);
125
                    if ($description == 'required' && empty(trim($required))) {
126
                        $required = $description;
127
                        $description = '';
128
                    }
129
                    $required = trim($required) == 'required' ? true : false;
130
                }
131
132
                $type = $this->normalizeParameterType($type);
133
                list($description, $example) = $this->parseDescription($description, $type);
134
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;
135
136
                return [$name => compact('type', 'description', 'required', 'value')];
137
            })->toArray();
138
139
        return $parameters;
140
    }
141
142
    /**
143
     * @param array $tags
144
     *
145
     * @return array
146
     */
147
    protected function getQueryParametersFromDocBlock(array $tags)
148
    {
149
        $parameters = collect($tags)
150
            ->filter(function ($tag) {
151
                return $tag instanceof Tag && $tag->getName() === 'queryParam';
152
            })
153
            ->mapWithKeys(function ($tag) {
154
                preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
155 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...
156
                    // this means only name was supplied
157
                    list($name) = preg_split('/\s+/', $tag->getContent());
158
                    $required = false;
159
                    $description = '';
160
                } else {
161
                    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...
162
                    $description = trim($description);
163
                    if ($description == 'required' && empty(trim($required))) {
164
                        $required = $description;
165
                        $description = '';
166
                    }
167
                    $required = trim($required) == 'required' ? true : false;
168
                }
169
170
                list($description, $value) = $this->parseDescription($description, 'string');
171
                if (is_null($value)) {
172
                    $value = str_contains($description, ['number', 'count', 'page'])
173
                        ? $this->generateDummyValue('integer')
174
                        : $this->generateDummyValue('string');
175
                }
176
177
                return [$name => compact('description', 'required', 'value')];
178
            })->toArray();
179
180
        return $parameters;
181
    }
182
183
    /**
184
     * @param array $tags
185
     *
186
     * @return bool
187
     */
188
    protected function getAuthStatusFromDocBlock(array $tags)
189
    {
190
        $authTag = collect($tags)
191
            ->first(function ($tag) {
192
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
193
            });
194
195
        return (bool) $authTag;
196
    }
197
198
    /**
199
     * @param ReflectionMethod $method
200
     *
201
     * @return array
202
     */
203
    protected function parseDocBlock(ReflectionMethod $method)
204
    {
205
        $comment = $method->getDocComment();
206
        $phpdoc = new DocBlock($comment);
207
208
        return [
209
            'short' => $phpdoc->getShortDescription(),
210
            'long' => $phpdoc->getLongDescription()->getContents(),
211
            'tags' => $phpdoc->getTags(),
212
        ];
213
    }
214
215
    /**
216
     * @param ReflectionClass $controller
217
     * @param ReflectionMethod $method
218
     *
219
     * @return string
220
     */
221
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
222
    {
223
        // @group tag on the method overrides that on the controller
224
        $docBlockComment = $method->getDocComment();
225 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...
226
            $phpdoc = new DocBlock($docBlockComment);
227
            foreach ($phpdoc->getTags() as $tag) {
228
                if ($tag->getName() === 'group') {
229
                    return $tag->getContent();
230
                }
231
            }
232
        }
233
234
        $docBlockComment = $controller->getDocComment();
235 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...
236
            $phpdoc = new DocBlock($docBlockComment);
237
            foreach ($phpdoc->getTags() as $tag) {
238
                if ($tag->getName() === 'group') {
239
                    return $tag->getContent();
240
                }
241
            }
242
        }
243
244
        return 'general';
245
    }
246
247
    private function normalizeParameterType($type)
248
    {
249
        $typeMap = [
250
            'int' => 'integer',
251
            'bool' => 'boolean',
252
            'double' => 'float',
253
        ];
254
255
        return $type ? ($typeMap[$type] ?? $type) : 'string';
256
    }
257
258
    private function generateDummyValue(string $type)
259
    {
260
        $faker = Factory::create();
261
        $fakes = [
262
            'integer' => function () {
263
                return rand(1, 20);
264
            },
265
            'number' => function () use ($faker) {
266
                return $faker->randomFloat();
267
            },
268
            'float' => function () use ($faker) {
269
                return $faker->randomFloat();
270
            },
271
            'boolean' => function () use ($faker) {
272
                return $faker->boolean();
273
            },
274
            'string' => function () use ($faker) {
275
                return str_random();
276
            },
277
            'array' => function () {
278
                return [];
279
            },
280
            'object' => function () {
281
                return new \stdClass;
282
            },
283
        ];
284
285
        $fake = $fakes[$type] ?? $fakes['string'];
286
287
        return $fake();
288
    }
289
290
    /**
291
     * Allows users to specify an example for the parameter by writing 'Example: the-example',
292
     * to be used in example requests and response calls.
293
     *
294
     * @param string $description
295
     * @param string $type The type of the parameter. Used to cast the example provided, if any.
296
     *
297
     * @return array The description and included example.
298
     */
299
    private function parseDescription(string $description, string $type)
300
    {
301
        $example = null;
302
        if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
303
            $description = $content[1];
304
305
            // examples are parsed as strings by default, we need to cast them properly
306
            $example = $this->castToType($content[2], $type);
307
        }
308
309
        return [$description, $example];
310
    }
311
312
    /**
313
     * Cast a value from a string to a specified type.
314
     *
315
     * @param string $value
316
     * @param string $type
317
     *
318
     * @return mixed
319
     */
320
    private function castToType(string $value, string $type)
321
    {
322
        $casts = [
323
            'integer' => 'intval',
324
            'number' => 'floatval',
325
            'float' => 'floatval',
326
            'boolean' => 'boolval',
327
        ];
328
329
        // First, we handle booleans. We can't use a regular cast,
330
        //because PHP considers string 'false' as true.
331
        if ($value == 'false' && $type == 'boolean') {
332
            return false;
333
        }
334
335
        if (isset($casts[$type])) {
336
            return $casts[$type]($value);
337
        }
338
339
        return $value;
340
    }
341
}
342