Completed
Push — master ( 19a354...96f998 )
by
unknown
02:07
created

Generator::processRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 9.472
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Mpociot\ApiDoc\Generators;
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\ResponseResolver;
12
13
class Generator
14
{
15
    /**
16
     * @param Route $route
17
     *
18
     * @return mixed
19
     */
20
    public function getUri(Route $route)
21
    {
22
        return $route->uri();
23
    }
24
25
    /**
26
     * @param Route $route
27
     *
28
     * @return mixed
29
     */
30
    public function getMethods(Route $route)
31
    {
32
        return array_diff($route->methods(), ['HEAD']);
33
    }
34
35
    /**
36
     * @param  \Illuminate\Routing\Route $route
37
     * @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...
38
     *
39
     * @return array
40
     */
41
    public function processRoute(Route $route, array $rulesToApply = [])
42
    {
43
        $routeAction = $route->getAction();
44
        list($class, $method) = explode('@', $routeAction['uses']);
45
        $controller = new ReflectionClass($class);
46
        $method = $controller->getMethod($method);
47
48
        $routeGroup = $this->getRouteGroup($controller, $method);
49
        $docBlock = $this->parseDocBlock($method);
50
        $content = ResponseResolver::getResponse($route, $docBlock['tags'], $rulesToApply);
51
52
        $parsedRoute = [
53
            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
54
            'group' => $routeGroup,
55
            'title' => $docBlock['short'],
56
            'description' => $docBlock['long'],
57
            'methods' => $this->getMethods($route),
58
            'uri' => $this->getUri($route),
59
            'bodyParameters' => $this->getBodyParametersFromDocBlock($docBlock['tags']),
60
            'queryParameters' => $this->getQueryParametersFromDocBlock($docBlock['tags']),
61
            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
62
            'response' => $content,
63
            'showresponse' => ! empty($content),
64
        ];
65
        $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
66
67
        return $parsedRoute;
68
    }
69
70
    /**
71
     * @param array $tags
72
     *
73
     * @return array
74
     */
75
    protected function getBodyParametersFromDocBlock(array $tags)
76
    {
77
        $parameters = collect($tags)
78
            ->filter(function ($tag) {
79
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
80
            })
81
            ->mapWithKeys(function ($tag) {
82
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
83 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...
84
                    // this means only name and type were supplied
85
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
86
                    $required = false;
87
                    $description = '';
88
                } else {
89
                    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...
90
                    $description = trim($description);
91
                    if ($description == 'required' && empty(trim($required))) {
92
                        $required = $description;
93
                        $description = '';
94
                    }
95
                    $required = trim($required) == 'required' ? true : false;
96
                }
97
98
                $type = $this->normalizeParameterType($type);
99
                $value = $this->generateDummyValue($type);
100
101
                return [$name => compact('type', 'description', 'required', 'value')];
102
            })->toArray();
103
104
        return $parameters;
105
    }
106
107
    /**
108
     * @param array $tags
109
     *
110
     * @return array
111
     */
112
    protected function getQueryParametersFromDocBlock(array $tags)
113
    {
114
        $parameters = collect($tags)
115
            ->filter(function ($tag) {
116
                return $tag instanceof Tag && $tag->getName() === 'queryParam';
117
            })
118
            ->mapWithKeys(function ($tag) {
119
                preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
120 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...
121
                    // this means only name was supplied
122
                    list($name) = preg_split('/\s+/', $tag->getContent());
123
                    $required = false;
124
                    $description = '';
125
                } else {
126
                    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...
127
                    $description = trim($description);
128
                    if ($description == 'required' && empty(trim($required))) {
129
                        $required = $description;
130
                        $description = '';
131
                    }
132
                    $required = trim($required) == 'required' ? true : false;
133
                }
134
135
                return [$name => compact('description', 'required')];
136
            })->toArray();
137
138
        return $parameters;
139
    }
140
141
    /**
142
     * @param array $tags
143
     *
144
     * @return bool
145
     */
146
    protected function getAuthStatusFromDocBlock(array $tags)
147
    {
148
        $authTag = collect($tags)
149
            ->first(function ($tag) {
150
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
151
            });
152
153
        return (bool) $authTag;
154
    }
155
156
    /**
157
     * @param ReflectionMethod $method
158
     *
159
     * @return array
160
     */
161
    protected function parseDocBlock(ReflectionMethod $method)
162
    {
163
        $comment = $method->getDocComment();
164
        $phpdoc = new DocBlock($comment);
165
166
        return [
167
            'short' => $phpdoc->getShortDescription(),
168
            'long' => $phpdoc->getLongDescription()->getContents(),
169
            'tags' => $phpdoc->getTags(),
170
        ];
171
    }
172
173
    /**
174
     * @param ReflectionClass $controller
175
     * @param ReflectionMethod $method
176
     *
177
     * @return string
178
     */
179
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
180
    {
181
        // @group tag on the method overrides that on the controller
182
        $docBlockComment = $method->getDocComment();
183 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...
184
            $phpdoc = new DocBlock($docBlockComment);
185
            foreach ($phpdoc->getTags() as $tag) {
186
                if ($tag->getName() === 'group') {
187
                    return $tag->getContent();
188
                }
189
            }
190
        }
191
192
        $docBlockComment = $controller->getDocComment();
193 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...
194
            $phpdoc = new DocBlock($docBlockComment);
195
            foreach ($phpdoc->getTags() as $tag) {
196
                if ($tag->getName() === 'group') {
197
                    return $tag->getContent();
198
                }
199
            }
200
        }
201
202
        return 'general';
203
    }
204
205
    private function normalizeParameterType($type)
206
    {
207
        $typeMap = [
208
            'int' => 'integer',
209
            'bool' => 'boolean',
210
            'double' => 'float',
211
        ];
212
213
        return $type ? ($typeMap[$type] ?? $type) : 'string';
214
    }
215
216
    private function generateDummyValue(string $type)
217
    {
218
        $faker = Factory::create();
219
        $fakes = [
220
            'integer' => function () {
221
                return rand(1, 20);
222
            },
223
            'number' => function () use ($faker) {
224
                return $faker->randomFloat();
225
            },
226
            'float' => function () use ($faker) {
227
                return $faker->randomFloat();
228
            },
229
            'boolean' => function () use ($faker) {
230
                return $faker->boolean();
231
            },
232
            'string' => function () use ($faker) {
233
                return str_random();
234
            },
235
            'array' => function () {
236
                return '[]';
237
            },
238
            'object' => function () {
239
                return '{}';
240
            },
241
        ];
242
243
        $fake = $fakes[$type] ?? $fakes['string'];
244
245
        return $fake();
246
    }
247
}
248