Completed
Pull Request — master (#369)
by
unknown
01:41
created

AbstractGenerator::parseDocBlock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Mpociot\ApiDoc\Generators;
4
5
use Faker\Factory;
6
use ReflectionClass;
7
use Illuminate\Support\Str;
8
use League\Fractal\Manager;
9
use Illuminate\Routing\Route;
10
use Mpociot\Reflection\DocBlock;
11
use League\Fractal\Resource\Item;
12
use Mpociot\Reflection\DocBlock\Tag;
13
use League\Fractal\Resource\Collection;
14
15
abstract class AbstractGenerator
16
{
17
    /**
18
     * @param Route $route
19
     *
20
     * @return mixed
21
     */
22
    public function getDomain(Route $route)
23
    {
24
        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...
25
    }
26
27
    /**
28
     * @param Route $route
29
     *
30
     * @return mixed
31
     */
32
    public function getUri(Route $route)
33
    {
34
        return $route->uri();
35
    }
36
37
    /**
38
     * @param Route $route
39
     *
40
     * @return mixed
41
     */
42
    public function getMethods(Route $route)
43
    {
44
        return array_diff($route->methods(), ['HEAD']);
45
    }
46
47
    /**
48
     * @param  \Illuminate\Routing\Route $route
49
     * @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...
50
     *
51
     * @return array
52
     */
53
    public function processRoute($route)
54
    {
55
        $routeAction = $route->getAction();
56
        $routeGroup = $this->getRouteGroup($routeAction['uses']);
57
        $docBlock = $this->parseDocBlock($routeAction['uses']);
58
        $content = $this->getResponse($docBlock['tags']);
59
60
        return [
61
            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
62
            'resource' => $routeGroup,
63
            'title' => $docBlock['short'],
64
            'description' => $docBlock['long'],
65
            'methods' => $this->getMethods($route),
66
            'uri' => $this->getUri($route),
67
            'parameters' => $this->getParametersFromDocBlock($docBlock['tags']),
68
            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
69
            'response' => $content,
70
            'showresponse' => ! empty($content),
71
        ];
72
    }
73
74
    /**
75
     * Prepares / Disables route middlewares.
76
     *
77
     * @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...
78
     *
79
     * @return  void
80
     */
81
    abstract public function prepareMiddleware($enable = false);
82
83
    /**
84
     * Get the response from the docblock if available.
85
     *
86
     * @param array $tags
87
     *
88
     * @return mixed
89
     */
90
    protected function getDocblockResponse($tags)
91
    {
92
        $responseTags = array_filter($tags, function ($tag) {
93
            return $tag instanceof Tag && \strtolower($tag->getName()) == 'response';
94
        });
95
        if (empty($responseTags)) {
96
            return;
97
        }
98
        $responseTag = \array_first($responseTags);
99
100
        return \response(json_encode($responseTag->getContent()), 200, ['Content-Type' => 'application/json']);
101
    }
102
103
    /**
104
     * @param array $tags
105
     *
106
     * @return array
107
     */
108
    protected function getParametersFromDocBlock(array $tags)
109
    {
110
        $parameters = collect($tags)
111
            ->filter(function ($tag) {
112
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
113
            })
114
            ->mapWithKeys(function ($tag) {
115
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
116
                if (empty($content)) {
117
                    // this means only name and type were supplied
118
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
119
                    $required = false;
120
                    $description = '';
121
                } else {
122
                    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...
123
                    $description = trim($description);
124
                    if ($description == 'required' && empty(trim($required))) {
125
                        $required = $description;
126
                        $description = '';
127
                    }
128
                    $required = trim($required) == 'required' ? true : false;
129
                }
130
131
                $type = $this->normalizeParameterType($type);
132
                $value = $this->generateDummyValue($type);
133
134
                return [$name => compact('type', 'description', 'required', 'value')];
135
            })->toArray();
136
137
        return $parameters;
138
    }
139
140
    /**
141
     * @param array $tags
142
     *
143
     * @return bool
144
     */
145
    protected function getAuthStatusFromDocBlock(array $tags)
146
    {
147
        $authTag = collect($tags)
148
            ->first(function ($tag) {
149
                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
150
            });
151
        return (bool) $authTag;
152
    }
153
154
    /**
155
     * @param  $route
156
     * @param  $bindings
157
     * @param  $headers
158
     *
159
     * @return \Illuminate\Http\Response
160
     */
161
    protected function getRouteResponse($route, $bindings, $headers = [])
162
    {
163
        $uri = $this->addRouteModelBindings($route, $bindings);
164
165
        $methods = $this->getMethods($route);
166
167
        // Split headers into key - value pairs
168
        $headers = collect($headers)->map(function ($value) {
169
            $split = explode(':', $value); // explode to get key + values
170
            $key = array_shift($split); // extract the key and keep the values in the array
171
            $value = implode(':', $split); // implode values into string again
172
173
            return [trim($key) => trim($value)];
174
        })->collapse()->toArray();
175
176
        //Changes url with parameters like /users/{user} to /users/1
177
        $uri = preg_replace('/{(.*?)}/', 1, $uri); // 1 is the default value for route parameters
178
179
        return $this->callRoute(array_shift($methods), $uri, [], [], [], $headers);
180
    }
181
182
    /**
183
     * @param $route
184
     * @param array $bindings
185
     *
186
     * @return mixed
187
     */
188
    protected function addRouteModelBindings($route, $bindings)
189
    {
190
        $uri = $this->getUri($route);
191
        foreach ($bindings as $model => $id) {
192
            $uri = str_replace('{'.$model.'}', $id, $uri);
193
            $uri = str_replace('{'.$model.'?}', $id, $uri);
194
        }
195
196
        return $uri;
197
    }
198
199
    /**
200
     * @param  \Illuminate\Routing\Route  $route
201
     *
202
     * @return array
203
     */
204
    protected function parseDocBlock($route)
205
    {
206
        list($class, $method) = explode('@', $route);
207
        $reflection = new ReflectionClass($class);
208
        $reflectionMethod = $reflection->getMethod($method);
209
210
        $comment = $reflectionMethod->getDocComment();
211
        $phpdoc = new DocBlock($comment);
212
213
        return [
214
            'short' => $phpdoc->getShortDescription(),
215
            'long' => $phpdoc->getLongDescription()->getContents(),
216
            'tags' => $phpdoc->getTags(),
217
        ];
218
    }
219
220
    /**
221
     * @param  string  $route
222
     *
223
     * @return string
224
     */
225
    protected function getRouteGroup($route)
226
    {
227
        list($class, $method) = explode('@', $route);
0 ignored issues
show
Unused Code introduced by
The assignment to $method 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...
228
        $reflection = new ReflectionClass($class);
229
        $comment = $reflection->getDocComment();
230
        if ($comment) {
231
            $phpdoc = new DocBlock($comment);
232
            foreach ($phpdoc->getTags() as $tag) {
233
                if ($tag->getName() === 'resource') {
234
                    return $tag->getContent();
235
                }
236
            }
237
        }
238
239
        return 'general';
240
    }
241
242
    /**
243
     * Call the given URI and return the Response.
244
     *
245
     * @param  string  $method
246
     * @param  string  $uri
247
     * @param  array  $parameters
248
     * @param  array  $cookies
249
     * @param  array  $files
250
     * @param  array  $server
251
     * @param  string  $content
252
     *
253
     * @return \Illuminate\Http\Response
254
     */
255
    abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
256
257
    /**
258
     * Transform headers array to array of $_SERVER vars with HTTP_* format.
259
     *
260
     * @param  array  $headers
261
     *
262
     * @return array
263
     */
264
    protected function transformHeadersToServerVars(array $headers)
265
    {
266
        $server = [];
267
        $prefix = 'HTTP_';
268
269
        foreach ($headers as $name => $value) {
270
            $name = strtr(strtoupper($name), '-', '_');
271
272
            if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
273
                $name = $prefix.$name;
274
            }
275
276
            $server[$name] = $value;
277
        }
278
279
        return $server;
280
    }
281
282
    /**
283
     * @param $response
284
     *
285
     * @return mixed
286
     */
287
    private function getResponseContent($response)
288
    {
289
        if (empty($response)) {
290
            return '';
291
        }
292
        if ($response->headers->get('Content-Type') === 'application/json') {
293
            $content = json_decode($response->getContent(), JSON_PRETTY_PRINT);
294
        } else {
295
            $content = $response->getContent();
296
        }
297
298
        return $content;
299
    }
300
301
    /**
302
     * Get a response from the transformer tags.
303
     *
304
     * @param array $tags
305
     *
306
     * @return mixed
307
     */
308
    protected function getTransformerResponse($tags)
309
    {
310
        try {
311
            $transFormerTags = array_filter($tags, function ($tag) {
312
                if (! ($tag instanceof Tag)) {
313
                    return false;
314
                }
315
316
                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
317
            });
318
            if (empty($transFormerTags)) {
319
                // we didn't have any of the tags so goodbye
320
                return false;
321
            }
322
323
            $modelTag = array_first(array_filter($tags, function ($tag) {
324
                if (! ($tag instanceof Tag)) {
325
                    return false;
326
                }
327
328
                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
329
            }));
330
            $tag = \array_first($transFormerTags);
331
            $transformer = $tag->getContent();
332
            if (! \class_exists($transformer)) {
333
                // if we can't find the transformer we can't generate a response
334
                return;
335
            }
336
            $demoData = [];
337
338
            $reflection = new ReflectionClass($transformer);
339
            $method = $reflection->getMethod('transform');
340
            $parameter = \array_first($method->getParameters());
341
            $type = null;
342
            if ($modelTag) {
343
                $type = $modelTag->getContent();
344
            }
345
            if (\is_null($type)) {
346
                if ($parameter->hasType() &&
347
                    ! $parameter->getType()->isBuiltin() &&
348
                    \class_exists((string) $parameter->getType())) {
349
                    //we have a type
350
                    $type = (string) $parameter->getType();
351
                }
352
            }
353
            if ($type) {
354
                // we have a class so we try to create an instance
355
                $demoData = new $type;
356
                try {
357
                    // try a factory
358
                    $demoData = \factory($type)->make();
359
                } catch (\Exception $e) {
360
                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
361
                        // we can't use a factory but can try to get one from the database
362
                        try {
363
                            // check if we can find one
364
                            $newDemoData = $type::first();
365
                            if ($newDemoData) {
366
                                $demoData = $newDemoData;
367
                            }
368
                        } catch (\Exception $e) {
369
                            // do nothing
370
                        }
371
                    }
372
                }
373
            }
374
375
            $fractal = new Manager();
376
            $resource = [];
377
            if ($tag->getName() == 'transformer') {
378
                // just one
379
                $resource = new Item($demoData, new $transformer);
380
            }
381
            if ($tag->getName() == 'transformercollection') {
382
                // a collection
383
                $resource = new Collection([$demoData, $demoData], new $transformer);
384
            }
385
386
            return \response($fractal->createData($resource)->toJson());
0 ignored issues
show
Bug introduced by
It seems like $resource defined by array() on line 376 can also be of type array; however, League\Fractal\Manager::createData() does only seem to accept object<League\Fractal\Resource\ResourceInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
387
        } catch (\Exception $e) {
388
            // it isn't possible to parse the transformer
389
            return;
390
        }
391
    }
392
393
    private function getResponse(array $annotationTags)
394
    {
395
        $response = null;
396
        if ($docblockResponse = $this->getDocblockResponse($annotationTags)) {
397
            // we have a response from the docblock ( @response )
398
            $response = $docblockResponse;
399
        }
400
        if (! $response && ($transformerResponse = $this->getTransformerResponse($annotationTags))) {
401
            // we have a transformer response from the docblock ( @transformer || @transformercollection )
402
            $response = $transformerResponse;
403
        }
404
405
        $content = $response ? $this->getResponseContent($response) : null;
406
407
        return $content;
408
    }
409
410
    private function normalizeParameterType($type)
411
    {
412
        $typeMap = [
413
            'int' => 'integer',
414
            'bool' => 'boolean',
415
            'double' => 'float',
416
        ];
417
418
        return $type ? ($typeMap[$type] ?? $type) : 'string';
419
    }
420
421
    private function generateDummyValue(string $type)
422
    {
423
        $faker = Factory::create();
424
        $fakes = [
425
            'integer' => function () {
426
                return rand(1, 20);
427
            },
428
            'number' => function () use ($faker) {
429
                return $faker->randomFloat();
430
            },
431
            'float' => function () use ($faker) {
432
                return $faker->randomFloat();
433
            },
434
            'boolean' => function () use ($faker) {
435
                return $faker->boolean();
436
            },
437
            'string' => function () use ($faker) {
438
                return str_random();
439
            },
440
            'array' => function () {
441
                return '[]';
442
            },
443
            'object' => function () {
444
                return '{}';
445
            },
446
        ];
447
448
        $fake = $fakes[$type] ?? $fakes['string'];
449
        return $fake();
450
    }
451
}
452