Completed
Push — master ( 15a84d...ee0f50 )
by
unknown
11s
created

AbstractGenerator::getRouteResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 1
nc 1
nop 3
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
            'response' => $content,
69
            'showresponse' => ! empty($content),
70
        ];
71
    }
72
73
    /**
74
     * Prepares / Disables route middlewares.
75
     *
76
     * @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...
77
     *
78
     * @return  void
79
     */
80
    abstract public function prepareMiddleware($enable = false);
81
82
    /**
83
     * Get the response from the docblock if available.
84
     *
85
     * @param array $tags
86
     *
87
     * @return mixed
88
     */
89
    protected function getDocblockResponse($tags)
90
    {
91
        $responseTags = array_filter($tags, function ($tag) {
92
            return $tag instanceof Tag && \strtolower($tag->getName()) == 'response';
93
        });
94
        if (empty($responseTags)) {
95
            return;
96
        }
97
        $responseTag = \array_first($responseTags);
98
99
        return \response(json_encode($responseTag->getContent()), 200, ['Content-Type' => 'application/json']);
100
    }
101
102
    /**
103
     * @param array $tags
104
     *
105
     * @return array
106
     */
107
    protected function getParametersFromDocBlock($tags)
108
    {
109
        $parameters = collect($tags)
110
            ->filter(function ($tag) {
111
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
112
            })
113
            ->mapWithKeys(function ($tag) {
114
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
115
                if (empty($content)) {
116
                    // this means only name and type were supplied
117
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
118
                    $required = false;
119
                    $description = '';
120
                } else {
121
                    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...
122
                    $description = trim($description);
123
                    if ($description == 'required' && empty(trim($required))) {
124
                        $required = $description;
125
                        $description = '';
126
                    }
127
                    $required = trim($required) == 'required' ? true : false;
128
                }
129
130
                $type = $this->normalizeParameterType($type);
131
                $value = $this->generateDummyValue($type);
132
133
                return [$name => compact('type', 'description', 'required', 'value')];
134
            })->toArray();
135
136
        return $parameters;
137
    }
138
139
    /**
140
     * @param  $route
141
     * @param  $bindings
142
     * @param  $headers
143
     *
144
     * @return \Illuminate\Http\Response
145
     */
146
    protected function getRouteResponse($route, $bindings, $headers = [])
147
    {
148
        $uri = $this->addRouteModelBindings($route, $bindings);
149
150
        $methods = $this->getMethods($route);
151
152
        // Split headers into key - value pairs
153
        $headers = collect($headers)->map(function ($value) {
154
            $split = explode(':', $value); // explode to get key + values
155
            $key = array_shift($split); // extract the key and keep the values in the array
156
            $value = implode(':', $split); // implode values into string again
157
158
            return [trim($key) => trim($value)];
159
        })->collapse()->toArray();
160
161
        //Changes url with parameters like /users/{user} to /users/1
162
        $uri = preg_replace('/{(.*?)}/', 1, $uri); // 1 is the default value for route parameters
163
164
        return $this->callRoute(array_shift($methods), $uri, [], [], [], $headers);
165
    }
166
167
    /**
168
     * @param $route
169
     * @param array $bindings
170
     *
171
     * @return mixed
172
     */
173
    protected function addRouteModelBindings($route, $bindings)
174
    {
175
        $uri = $this->getUri($route);
176
        foreach ($bindings as $model => $id) {
177
            $uri = str_replace('{'.$model.'}', $id, $uri);
178
            $uri = str_replace('{'.$model.'?}', $id, $uri);
179
        }
180
181
        return $uri;
182
    }
183
184
    /**
185
     * @param  \Illuminate\Routing\Route  $route
186
     *
187
     * @return array
188
     */
189
    protected function parseDocBlock($route)
190
    {
191
        list($class, $method) = explode('@', $route);
192
        $reflection = new ReflectionClass($class);
193
        $reflectionMethod = $reflection->getMethod($method);
194
195
        $comment = $reflectionMethod->getDocComment();
196
        $phpdoc = new DocBlock($comment);
197
198
        return [
199
            'short' => $phpdoc->getShortDescription(),
200
            'long' => $phpdoc->getLongDescription()->getContents(),
201
            'tags' => $phpdoc->getTags(),
202
        ];
203
    }
204
205
    /**
206
     * @param  string  $route
207
     *
208
     * @return string
209
     */
210
    protected function getRouteGroup($route)
211
    {
212
        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...
213
        $reflection = new ReflectionClass($class);
214
        $comment = $reflection->getDocComment();
215
        if ($comment) {
216
            $phpdoc = new DocBlock($comment);
217
            foreach ($phpdoc->getTags() as $tag) {
218
                if ($tag->getName() === 'resource') {
219
                    return $tag->getContent();
220
                }
221
            }
222
        }
223
224
        return 'general';
225
    }
226
227
    /**
228
     * Call the given URI and return the Response.
229
     *
230
     * @param  string  $method
231
     * @param  string  $uri
232
     * @param  array  $parameters
233
     * @param  array  $cookies
234
     * @param  array  $files
235
     * @param  array  $server
236
     * @param  string  $content
237
     *
238
     * @return \Illuminate\Http\Response
239
     */
240
    abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
241
242
    /**
243
     * Transform headers array to array of $_SERVER vars with HTTP_* format.
244
     *
245
     * @param  array  $headers
246
     *
247
     * @return array
248
     */
249
    protected function transformHeadersToServerVars(array $headers)
250
    {
251
        $server = [];
252
        $prefix = 'HTTP_';
253
254
        foreach ($headers as $name => $value) {
255
            $name = strtr(strtoupper($name), '-', '_');
256
257
            if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
258
                $name = $prefix.$name;
259
            }
260
261
            $server[$name] = $value;
262
        }
263
264
        return $server;
265
    }
266
267
    /**
268
     * @param $response
269
     *
270
     * @return mixed
271
     */
272
    private function getResponseContent($response)
273
    {
274
        if (empty($response)) {
275
            return '';
276
        }
277
        if ($response->headers->get('Content-Type') === 'application/json') {
278
            $content = json_decode($response->getContent(), JSON_PRETTY_PRINT);
279
        } else {
280
            $content = $response->getContent();
281
        }
282
283
        return $content;
284
    }
285
286
    /**
287
     * Get a response from the transformer tags.
288
     *
289
     * @param array $tags
290
     *
291
     * @return mixed
292
     */
293
    protected function getTransformerResponse($tags)
294
    {
295
        try {
296
            $transFormerTags = array_filter($tags, function ($tag) {
297
                if (! ($tag instanceof Tag)) {
298
                    return false;
299
                }
300
301
                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
302
            });
303
            if (empty($transFormerTags)) {
304
                // we didn't have any of the tags so goodbye
305
                return false;
306
            }
307
308
            $modelTag = array_first(array_filter($tags, function ($tag) {
309
                if (! ($tag instanceof Tag)) {
310
                    return false;
311
                }
312
313
                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
314
            }));
315
            $tag = \array_first($transFormerTags);
316
            $transformer = $tag->getContent();
317
            if (! \class_exists($transformer)) {
318
                // if we can't find the transformer we can't generate a response
319
                return;
320
            }
321
            $demoData = [];
322
323
            $reflection = new ReflectionClass($transformer);
324
            $method = $reflection->getMethod('transform');
325
            $parameter = \array_first($method->getParameters());
326
            $type = null;
327
            if ($modelTag) {
328
                $type = $modelTag->getContent();
329
            }
330
            if (\is_null($type)) {
331
                if ($parameter->hasType() &&
332
                    ! $parameter->getType()->isBuiltin() &&
333
                    \class_exists((string) $parameter->getType())) {
334
                    //we have a type
335
                    $type = (string) $parameter->getType();
336
                }
337
            }
338
            if ($type) {
339
                // we have a class so we try to create an instance
340
                $demoData = new $type;
341
                try {
342
                    // try a factory
343
                    $demoData = \factory($type)->make();
344
                } catch (\Exception $e) {
345
                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
346
                        // we can't use a factory but can try to get one from the database
347
                        try {
348
                            // check if we can find one
349
                            $newDemoData = $type::first();
350
                            if ($newDemoData) {
351
                                $demoData = $newDemoData;
352
                            }
353
                        } catch (\Exception $e) {
354
                            // do nothing
355
                        }
356
                    }
357
                }
358
            }
359
360
            $fractal = new Manager();
361
            $resource = [];
362
            if ($tag->getName() == 'transformer') {
363
                // just one
364
                $resource = new Item($demoData, new $transformer);
365
            }
366
            if ($tag->getName() == 'transformercollection') {
367
                // a collection
368
                $resource = new Collection([$demoData, $demoData], new $transformer);
369
            }
370
371
            return \response($fractal->createData($resource)->toJson());
0 ignored issues
show
Bug introduced by
It seems like $resource defined by array() on line 361 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...
372
        } catch (\Exception $e) {
373
            // it isn't possible to parse the transformer
374
            return;
375
        }
376
    }
377
378
    private function getResponse(array $annotationTags)
379
    {
380
        $response = null;
381
        if ($docblockResponse = $this->getDocblockResponse($annotationTags)) {
382
            // we have a response from the docblock ( @response )
383
            $response = $docblockResponse;
384
        }
385
        if (! $response && ($transformerResponse = $this->getTransformerResponse($annotationTags))) {
386
            // we have a transformer response from the docblock ( @transformer || @transformercollection )
387
            $response = $transformerResponse;
388
        }
389
390
        $content = $response ? $this->getResponseContent($response) : null;
391
392
        return $content;
393
    }
394
395
    private function normalizeParameterType($type)
396
    {
397
        $typeMap = [
398
            'int' => 'integer',
399
            'bool' => 'boolean',
400
            'double' => 'float',
401
        ];
402
403
        return $type ? ($typeMap[$type] ?? $type) : 'string';
404
    }
405
406
    private function generateDummyValue(string $type)
407
    {
408
        $faker = Factory::create();
409
        $fakes = [
410
            'integer' => function () {
411
                return rand(1, 20);
412
            },
413
            'number' => function () use ($faker) {
414
                return $faker->randomFloat();
415
            },
416
            'float' => function () use ($faker) {
417
                return $faker->randomFloat();
418
            },
419
            'boolean' => function () use ($faker) {
420
                return $faker->boolean();
421
            },
422
            'string' => function () use ($faker) {
423
                return str_random();
424
            },
425
            'array' => function () {
426
                return '[]';
427
            },
428
            'object' => function () {
429
                return '{}';
430
            },
431
        ];
432
433
        return $fakes[$type]() ?? $fakes['string']();
434
    }
435
}
436