Completed
Push — master ( 92226e...f16dbe )
by
unknown
22s
created

Generator::getRouteGroup()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 25

Duplication

Lines 16
Ratio 64 %

Importance

Changes 0
Metric Value
dl 16
loc 25
rs 8.5866
c 0
b 0
f 0
cc 7
nc 7
nop 2
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
                $value = $this->generateDummyValue($type);
105
106
                return [$name => compact('type', 'description', 'required', 'value')];
107
            })->toArray();
108
109
        return $parameters;
110
    }
111
112
    /**
113
     * @param array $tags
114
     *
115
     * @return array
116
     */
117
    protected function getQueryParametersFromDocBlock(array $tags)
118
    {
119
        $parameters = collect($tags)
120
            ->filter(function ($tag) {
121
                return $tag instanceof Tag && $tag->getName() === 'queryParam';
122
            })
123
            ->mapWithKeys(function ($tag) {
124
                preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
125 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...
126
                    // this means only name was supplied
127
                    list($name) = preg_split('/\s+/', $tag->getContent());
128
                    $required = false;
129
                    $description = '';
130
                } else {
131
                    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...
132
                    $description = trim($description);
133
                    if ($description == 'required' && empty(trim($required))) {
134
                        $required = $description;
135
                        $description = '';
136
                    }
137
                    $required = trim($required) == 'required' ? true : false;
138
                }
139
140
                if (str_contains($description, ['number', 'count', 'page'])) {
141
                    $value = $this->generateDummyValue('integer');
142
                } else {
143
                    $value = $this->generateDummyValue('string');
144
                }
145
146
                return [$name => compact('description', 'required', 'value')];
147
            })->toArray();
148
149
        return $parameters;
150
    }
151
152
    /**
153
     * @param array $tags
154
     *
155
     * @return bool
156
     */
157
    protected function getAuthStatusFromDocBlock(array $tags)
158
    {
159
        $authTag = collect($tags)
160
            ->first(function ($tag) {
161
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
162
            });
163
164
        return (bool) $authTag;
165
    }
166
167
    /**
168
     * @param ReflectionMethod $method
169
     *
170
     * @return array
171
     */
172
    protected function parseDocBlock(ReflectionMethod $method)
173
    {
174
        $comment = $method->getDocComment();
175
        $phpdoc = new DocBlock($comment);
176
177
        return [
178
            'short' => $phpdoc->getShortDescription(),
179
            'long' => $phpdoc->getLongDescription()->getContents(),
180
            'tags' => $phpdoc->getTags(),
181
        ];
182
    }
183
184
    /**
185
     * @param ReflectionClass $controller
186
     * @param ReflectionMethod $method
187
     *
188
     * @return string
189
     */
190
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
191
    {
192
        // @group tag on the method overrides that on the controller
193
        $docBlockComment = $method->getDocComment();
194 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...
195
            $phpdoc = new DocBlock($docBlockComment);
196
            foreach ($phpdoc->getTags() as $tag) {
197
                if ($tag->getName() === 'group') {
198
                    return $tag->getContent();
199
                }
200
            }
201
        }
202
203
        $docBlockComment = $controller->getDocComment();
204 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...
205
            $phpdoc = new DocBlock($docBlockComment);
206
            foreach ($phpdoc->getTags() as $tag) {
207
                if ($tag->getName() === 'group') {
208
                    return $tag->getContent();
209
                }
210
            }
211
        }
212
213
        return 'general';
214
    }
215
216
    private function normalizeParameterType($type)
217
    {
218
        $typeMap = [
219
            'int' => 'integer',
220
            'bool' => 'boolean',
221
            'double' => 'float',
222
        ];
223
224
        return $type ? ($typeMap[$type] ?? $type) : 'string';
225
    }
226
227
    private function generateDummyValue(string $type)
228
    {
229
        $faker = Factory::create();
230
        $fakes = [
231
            'integer' => function () {
232
                return rand(1, 20);
233
            },
234
            'number' => function () use ($faker) {
235
                return $faker->randomFloat();
236
            },
237
            'float' => function () use ($faker) {
238
                return $faker->randomFloat();
239
            },
240
            'boolean' => function () use ($faker) {
241
                return $faker->boolean();
242
            },
243
            'string' => function () use ($faker) {
244
                return str_random();
245
            },
246
            'array' => function () {
247
                return '[]';
248
            },
249
            'object' => function () {
250
                return '{}';
251
            },
252
        ];
253
254
        $fake = $fakes[$type] ?? $fakes['string'];
255
256
        return $fake();
257
    }
258
}
259