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

AbstractGenerator::callRoute()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 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
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  $route
202
     *
203
     * @return array
204
     */
205
    protected function parseDocBlock($route)
206
    {
207
        list($class, $method) = explode('@', $route);
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  $route
223
     *
224
     * @return string
225
     */
226
    protected function getRouteGroup($route)
227
    {
228
        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...
229
        $reflection = new ReflectionClass($class);
230
        $comment = $reflection->getDocComment();
231
        if ($comment) {
232
            $phpdoc = new DocBlock($comment);
233
            foreach ($phpdoc->getTags() as $tag) {
234
                if ($tag->getName() === 'resource') {
235
                    return $tag->getContent();
236
                }
237
            }
238
        }
239
240
        return 'general';
241
    }
242
243
    /**
244
     * Call the given URI and return the Response.
245
     *
246
     * @param  string  $method
247
     * @param  string  $uri
248
     * @param  array  $parameters
249
     * @param  array  $cookies
250
     * @param  array  $files
251
     * @param  array  $server
252
     * @param  string  $content
253
     *
254
     * @return \Illuminate\Http\Response
255
     */
256
    abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
257
258
    /**
259
     * Transform headers array to array of $_SERVER vars with HTTP_* format.
260
     *
261
     * @param  array  $headers
262
     *
263
     * @return array
264
     */
265
    protected function transformHeadersToServerVars(array $headers)
266
    {
267
        $server = [];
268
        $prefix = 'HTTP_';
269
270
        foreach ($headers as $name => $value) {
271
            $name = strtr(strtoupper($name), '-', '_');
272
273
            if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
274
                $name = $prefix.$name;
275
            }
276
277
            $server[$name] = $value;
278
        }
279
280
        return $server;
281
    }
282
283
    /**
284
     * @param $response
285
     *
286
     * @return mixed
287
     */
288
    private function getResponseContent($response)
289
    {
290
        if (empty($response)) {
291
            return '';
292
        }
293
        if ($response->headers->get('Content-Type') === 'application/json') {
294
            $content = json_decode($response->getContent(), JSON_PRETTY_PRINT);
295
        } else {
296
            $content = $response->getContent();
297
        }
298
299
        return $content;
300
    }
301
302
    /**
303
     * Get a response from the transformer tags.
304
     *
305
     * @param array $tags
306
     *
307
     * @return mixed
308
     */
309
    protected function getTransformerResponse($tags)
310
    {
311
        try {
312
            $transFormerTags = array_filter($tags, function ($tag) {
313
                if (! ($tag instanceof Tag)) {
314
                    return false;
315
                }
316
317
                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
318
            });
319
            if (empty($transFormerTags)) {
320
                // we didn't have any of the tags so goodbye
321
                return false;
322
            }
323
324
            $modelTag = array_first(array_filter($tags, function ($tag) {
325
                if (! ($tag instanceof Tag)) {
326
                    return false;
327
                }
328
329
                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
330
            }));
331
            $tag = \array_first($transFormerTags);
332
            $transformer = $tag->getContent();
333
            if (! \class_exists($transformer)) {
334
                // if we can't find the transformer we can't generate a response
335
                return;
336
            }
337
            $demoData = [];
338
339
            $reflection = new ReflectionClass($transformer);
340
            $method = $reflection->getMethod('transform');
341
            $parameter = \array_first($method->getParameters());
342
            $type = null;
343
            if ($modelTag) {
344
                $type = $modelTag->getContent();
345
            }
346
            if (\is_null($type)) {
347
                if ($parameter->hasType() &&
348
                    ! $parameter->getType()->isBuiltin() &&
349
                    \class_exists((string) $parameter->getType())) {
350
                    //we have a type
351
                    $type = (string) $parameter->getType();
352
                }
353
            }
354
            if ($type) {
355
                // we have a class so we try to create an instance
356
                $demoData = new $type;
357
                try {
358
                    // try a factory
359
                    $demoData = \factory($type)->make();
360
                } catch (\Exception $e) {
361
                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
362
                        // we can't use a factory but can try to get one from the database
363
                        try {
364
                            // check if we can find one
365
                            $newDemoData = $type::first();
366
                            if ($newDemoData) {
367
                                $demoData = $newDemoData;
368
                            }
369
                        } catch (\Exception $e) {
370
                            // do nothing
371
                        }
372
                    }
373
                }
374
            }
375
376
            $fractal = new Manager();
377
            $resource = [];
378
            if ($tag->getName() == 'transformer') {
379
                // just one
380
                $resource = new Item($demoData, new $transformer);
381
            }
382
            if ($tag->getName() == 'transformercollection') {
383
                // a collection
384
                $resource = new Collection([$demoData, $demoData], new $transformer);
385
            }
386
387
            return \response($fractal->createData($resource)->toJson());
0 ignored issues
show
Bug introduced by
It seems like $resource defined by array() on line 377 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...
388
        } catch (\Exception $e) {
389
            // it isn't possible to parse the transformer
390
            return;
391
        }
392
    }
393
394
    private function getResponse(array $annotationTags)
395
    {
396
        $response = null;
397
        if ($docblockResponse = $this->getDocblockResponse($annotationTags)) {
398
            // we have a response from the docblock ( @response )
399
            $response = $docblockResponse;
400
        }
401
        if (! $response && ($transformerResponse = $this->getTransformerResponse($annotationTags))) {
402
            // we have a transformer response from the docblock ( @transformer || @transformercollection )
403
            $response = $transformerResponse;
404
        }
405
406
        $content = $response ? $this->getResponseContent($response) : null;
407
408
        return $content;
409
    }
410
411
    private function normalizeParameterType($type)
412
    {
413
        $typeMap = [
414
            'int' => 'integer',
415
            'bool' => 'boolean',
416
            'double' => 'float',
417
        ];
418
419
        return $type ? ($typeMap[$type] ?? $type) : 'string';
420
    }
421
422
    private function generateDummyValue(string $type)
423
    {
424
        $faker = Factory::create();
425
        $fakes = [
426
            'integer' => function () {
427
                return rand(1, 20);
428
            },
429
            'number' => function () use ($faker) {
430
                return $faker->randomFloat();
431
            },
432
            'float' => function () use ($faker) {
433
                return $faker->randomFloat();
434
            },
435
            'boolean' => function () use ($faker) {
436
                return $faker->boolean();
437
            },
438
            'string' => function () use ($faker) {
439
                return str_random();
440
            },
441
            'array' => function () {
442
                return '[]';
443
            },
444
            'object' => function () {
445
                return '{}';
446
            },
447
        ];
448
449
        $fake = $fakes[$type] ?? $fakes['string'];
450
451
        return $fake();
452
    }
453
}
454