Completed
Pull Request — master (#376)
by
unknown
01:48
created

AbstractGenerator::transformHeadersToServerVars()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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