Completed
Pull Request — master (#377)
by
unknown
01:45
created

Generator::processRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 9.488
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
            'parameters' => $this->getParametersFromDocBlock($docBlock['tags']),
60
            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
61
            'response' => $content,
62
            'showresponse' => ! empty($content),
63
        ];
64
        $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
65
66
        return $parsedRoute;
67
    }
68
69
    /**
70
     * @param array $tags
71
     *
72
     * @return array
73
     */
74
    protected function getParametersFromDocBlock(array $tags)
75
    {
76
        $parameters = collect($tags)
77
            ->filter(function ($tag) {
78
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
79
            })
80
            ->mapWithKeys(function ($tag) {
81
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
82
                if (empty($content)) {
83
                    // this means only name and type were supplied
84
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
85
                    $required = false;
86
                    $description = '';
87
                } else {
88
                    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...
89
                    $description = trim($description);
90
                    if ($description == 'required' && empty(trim($required))) {
91
                        $required = $description;
92
                        $description = '';
93
                    }
94
                    $required = trim($required) == 'required' ? true : false;
95
                }
96
97
                $type = $this->normalizeParameterType($type);
98
                $value = $this->generateDummyValue($type);
99
100
                return [$name => compact('type', 'description', 'required', 'value')];
101
            })->toArray();
102
103
        return $parameters;
104
    }
105
106
    /**
107
     * @param array $tags
108
     *
109
     * @return bool
110
     */
111
    protected function getAuthStatusFromDocBlock(array $tags)
112
    {
113
        $authTag = collect($tags)
114
            ->first(function ($tag) {
115
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
116
            });
117
118
        return (bool) $authTag;
119
    }
120
121
    /**
122
     * @param ReflectionMethod $method
123
     *
124
     * @return array
125
     */
126
    protected function parseDocBlock(ReflectionMethod $method)
127
    {
128
        $comment = $method->getDocComment();
129
        $phpdoc = new DocBlock($comment);
130
131
        return [
132
            'short' => $phpdoc->getShortDescription(),
133
            'long' => $phpdoc->getLongDescription()->getContents(),
134
            'tags' => $phpdoc->getTags(),
135
        ];
136
    }
137
138
    /**
139
     * @param ReflectionClass $controller
140
     * @param ReflectionMethod $method
141
     *
142
     * @return string
143
     */
144
    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
145
    {
146
        // @group tag on the method overrides that on the controller
147
        $docBlockComment = $method->getDocComment();
148 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...
149
            $phpdoc = new DocBlock($docBlockComment);
150
            foreach ($phpdoc->getTags() as $tag) {
151
                if ($tag->getName() === 'group') {
152
                    return $tag->getContent();
153
                }
154
            }
155
        }
156
157
        $docBlockComment = $controller->getDocComment();
158 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...
159
            $phpdoc = new DocBlock($docBlockComment);
160
            foreach ($phpdoc->getTags() as $tag) {
161
                if ($tag->getName() === 'group') {
162
                    return $tag->getContent();
163
                }
164
            }
165
        }
166
167
        return 'general';
168
    }
169
170
    private function normalizeParameterType($type)
171
    {
172
        $typeMap = [
173
            'int' => 'integer',
174
            'bool' => 'boolean',
175
            'double' => 'float',
176
        ];
177
178
        return $type ? ($typeMap[$type] ?? $type) : 'string';
179
    }
180
181
    private function generateDummyValue(string $type)
182
    {
183
        $faker = Factory::create();
184
        $fakes = [
185
            'integer' => function () {
186
                return rand(1, 20);
187
            },
188
            'number' => function () use ($faker) {
189
                return $faker->randomFloat();
190
            },
191
            'float' => function () use ($faker) {
192
                return $faker->randomFloat();
193
            },
194
            'boolean' => function () use ($faker) {
195
                return $faker->boolean();
196
            },
197
            'string' => function () use ($faker) {
198
                return str_random();
199
            },
200
            'array' => function () {
201
                return '[]';
202
            },
203
            'object' => function () {
204
                return '{}';
205
            },
206
        ];
207
208
        $fake = $fakes[$type] ?? $fakes['string'];
209
210
        return $fake();
211
    }
212
}
213