Completed
Push — master ( 0be612...adc96f )
by
unknown
25s
created

AbstractGenerator::getDomain()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
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
            'group' => $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
152
        return (bool) $authTag;
153
    }
154
155
    /**
156
     * @param  $route
157
     * @param  $bindings
158
     * @param  $headers
159
     *
160
     * @return \Illuminate\Http\Response
161
     */
162
    protected function getRouteResponse($route, $bindings, $headers = [])
163
    {
164
        $uri = $this->addRouteModelBindings($route, $bindings);
165
166
        $methods = $this->getMethods($route);
167
168
        // Split headers into key - value pairs
169
        $headers = collect($headers)->map(function ($value) {
170
            $split = explode(':', $value); // explode to get key + values
171
            $key = array_shift($split); // extract the key and keep the values in the array
172
            $value = implode(':', $split); // implode values into string again
173
174
            return [trim($key) => trim($value)];
175
        })->collapse()->toArray();
176
177
        //Changes url with parameters like /users/{user} to /users/1
178
        $uri = preg_replace('/{(.*?)}/', 1, $uri); // 1 is the default value for route parameters
179
180
        return $this->callRoute(array_shift($methods), $uri, [], [], [], $headers);
181
    }
182
183
    /**
184
     * @param $route
185
     * @param array $bindings
186
     *
187
     * @return mixed
188
     */
189
    protected function addRouteModelBindings($route, $bindings)
190
    {
191
        $uri = $this->getUri($route);
192
        foreach ($bindings as $model => $id) {
193
            $uri = str_replace('{'.$model.'}', $id, $uri);
194
            $uri = str_replace('{'.$model.'?}', $id, $uri);
195
        }
196
197
        return $uri;
198
    }
199
200
    /**
201
     * @param  \Illuminate\Routing\Route  $routeAction
202
     *
203
     * @return array
204
     */
205
    protected function parseDocBlock(string $routeAction)
206
    {
207
        list($class, $method) = explode('@', $routeAction);
208
        $reflection = new ReflectionClass($class);
209
        $reflectionMethod = $reflection->getMethod($method);
210
211
        $comment = $reflectionMethod->getDocComment();
212
        $phpdoc = new DocBlock($comment);
213
214
        return [
215
            'short' => $phpdoc->getShortDescription(),
216
            'long' => $phpdoc->getLongDescription()->getContents(),
217
            'tags' => $phpdoc->getTags(),
218
        ];
219
    }
220
221
    /**
222
     * @param  string  $routeAction
223
     *
224
     * @return string
225
     */
226
    protected function getRouteGroup(string $routeAction)
227
    {
228
        list($class, $method) = explode('@', $routeAction);
229
        $controller = new ReflectionClass($class);
230
231
        // @group tag on the method overrides that on the controller
232
        $method = $controller->getMethod($method);
233
        $docBlockComment = $method->getDocComment();
234 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...
235
            $phpdoc = new DocBlock($docBlockComment);
236
            foreach ($phpdoc->getTags() as $tag) {
237
                if ($tag->getName() === 'group') {
238
                    return $tag->getContent();
239
                }
240
            }
241
        }
242
243
        $docBlockComment = $controller->getDocComment();
244 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...
245
            $phpdoc = new DocBlock($docBlockComment);
246
            foreach ($phpdoc->getTags() as $tag) {
247
                if ($tag->getName() === 'group') {
248
                    return $tag->getContent();
249
                }
250
            }
251
        }
252
253
        return 'general';
254
    }
255
256
    /**
257
     * Call the given URI and return the Response.
258
     *
259
     * @param  string  $method
260
     * @param  string  $uri
261
     * @param  array  $parameters
262
     * @param  array  $cookies
263
     * @param  array  $files
264
     * @param  array  $server
265
     * @param  string  $content
266
     *
267
     * @return \Illuminate\Http\Response
268
     */
269
    abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
270
271
    /**
272
     * Transform headers array to array of $_SERVER vars with HTTP_* format.
273
     *
274
     * @param  array  $headers
275
     *
276
     * @return array
277
     */
278
    protected function transformHeadersToServerVars(array $headers)
279
    {
280
        $server = [];
281
        $prefix = 'HTTP_';
282
283
        foreach ($headers as $name => $value) {
284
            $name = strtr(strtoupper($name), '-', '_');
285
286
            if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
287
                $name = $prefix.$name;
288
            }
289
290
            $server[$name] = $value;
291
        }
292
293
        return $server;
294
    }
295
296
    /**
297
     * @param $response
298
     *
299
     * @return mixed
300
     */
301
    private function getResponseContent($response)
302
    {
303
        if (empty($response)) {
304
            return '';
305
        }
306
        if ($response->headers->get('Content-Type') === 'application/json') {
307
            $content = json_decode($response->getContent(), JSON_PRETTY_PRINT);
308
        } else {
309
            $content = $response->getContent();
310
        }
311
312
        return $content;
313
    }
314
315
    /**
316
     * Get a response from the transformer tags.
317
     *
318
     * @param array $tags
319
     *
320
     * @return mixed
321
     */
322
    protected function getTransformerResponse($tags)
323
    {
324
        try {
325
            $transFormerTags = array_filter($tags, function ($tag) {
326
                if (! ($tag instanceof Tag)) {
327
                    return false;
328
                }
329
330
                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
331
            });
332
            if (empty($transFormerTags)) {
333
                // we didn't have any of the tags so goodbye
334
                return false;
335
            }
336
337
            $modelTag = array_first(array_filter($tags, function ($tag) {
338
                if (! ($tag instanceof Tag)) {
339
                    return false;
340
                }
341
342
                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
343
            }));
344
            $tag = \array_first($transFormerTags);
345
            $transformer = $tag->getContent();
346
            if (! \class_exists($transformer)) {
347
                // if we can't find the transformer we can't generate a response
348
                return;
349
            }
350
            $demoData = [];
351
352
            $reflection = new ReflectionClass($transformer);
353
            $method = $reflection->getMethod('transform');
354
            $parameter = \array_first($method->getParameters());
355
            $type = null;
356
            if ($modelTag) {
357
                $type = $modelTag->getContent();
358
            }
359
            if (\is_null($type)) {
360
                if ($parameter->hasType() &&
361
                    ! $parameter->getType()->isBuiltin() &&
362
                    \class_exists((string) $parameter->getType())) {
363
                    //we have a type
364
                    $type = (string) $parameter->getType();
365
                }
366
            }
367
            if ($type) {
368
                // we have a class so we try to create an instance
369
                $demoData = new $type;
370
                try {
371
                    // try a factory
372
                    $demoData = \factory($type)->make();
373
                } catch (\Exception $e) {
374
                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
375
                        // we can't use a factory but can try to get one from the database
376
                        try {
377
                            // check if we can find one
378
                            $newDemoData = $type::first();
379
                            if ($newDemoData) {
380
                                $demoData = $newDemoData;
381
                            }
382
                        } catch (\Exception $e) {
383
                            // do nothing
384
                        }
385
                    }
386
                }
387
            }
388
389
            $fractal = new Manager();
390
            $resource = [];
391
            if ($tag->getName() == 'transformer') {
392
                // just one
393
                $resource = new Item($demoData, new $transformer);
394
            }
395
            if ($tag->getName() == 'transformercollection') {
396
                // a collection
397
                $resource = new Collection([$demoData, $demoData], new $transformer);
398
            }
399
400
            return \response($fractal->createData($resource)->toJson());
0 ignored issues
show
Bug introduced by
It seems like $resource defined by array() on line 390 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...
401
        } catch (\Exception $e) {
402
            // it isn't possible to parse the transformer
403
            return;
404
        }
405
    }
406
407
    private function getResponse(array $annotationTags)
408
    {
409
        $response = null;
410
        if ($docblockResponse = $this->getDocblockResponse($annotationTags)) {
411
            // we have a response from the docblock ( @response )
412
            $response = $docblockResponse;
413
        }
414
        if (! $response && ($transformerResponse = $this->getTransformerResponse($annotationTags))) {
415
            // we have a transformer response from the docblock ( @transformer || @transformercollection )
416
            $response = $transformerResponse;
417
        }
418
419
        $content = $response ? $this->getResponseContent($response) : null;
420
421
        return $content;
422
    }
423
424
    private function normalizeParameterType($type)
425
    {
426
        $typeMap = [
427
            'int' => 'integer',
428
            'bool' => 'boolean',
429
            'double' => 'float',
430
        ];
431
432
        return $type ? ($typeMap[$type] ?? $type) : 'string';
433
    }
434
435
    private function generateDummyValue(string $type)
436
    {
437
        $faker = Factory::create();
438
        $fakes = [
439
            'integer' => function () {
440
                return rand(1, 20);
441
            },
442
            'number' => function () use ($faker) {
443
                return $faker->randomFloat();
444
            },
445
            'float' => function () use ($faker) {
446
                return $faker->randomFloat();
447
            },
448
            'boolean' => function () use ($faker) {
449
                return $faker->boolean();
450
            },
451
            'string' => function () use ($faker) {
452
                return str_random();
453
            },
454
            'array' => function () {
455
                return '[]';
456
            },
457
            'object' => function () {
458
                return '{}';
459
            },
460
        ];
461
462
        $fake = $fakes[$type] ?? $fakes['string'];
463
464
        return $fake();
465
    }
466
}
467