Completed
Pull Request — master (#323)
by
unknown
01:31
created

AbstractGenerator::parseRule()   F

Complexity

Conditions 57
Paths 220

Size

Total Lines 210

Duplication

Lines 96
Ratio 45.71 %

Importance

Changes 0
Metric Value
dl 96
loc 210
rs 2.4666
c 0
b 0
f 0
cc 57
nc 220
nop 5

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Mpociot\ApiDoc\Generators;
4
5
use Faker\Factory;
6
use League\Fractal\Manager;
7
use League\Fractal\Resource\Collection;
8
use League\Fractal\Resource\Item;
9
use ReflectionClass;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Str;
12
use Mpociot\Reflection\DocBlock;
13
use Mpociot\Reflection\DocBlock\Tag;
14
use Illuminate\Support\Facades\Validator;
15
use Illuminate\Foundation\Http\FormRequest;
16
use Mpociot\ApiDoc\Parsers\RuleDescriptionParser as Description;
17
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
18
19
abstract class AbstractGenerator
20
{
21
    /**
22
     * @param $route
23
     *
24
     * @return mixed
25
     */
26
    abstract public function getDomain($route);
27
28
    /**
29
     * @param $route
30
     *
31
     * @return mixed
32
     */
33
    abstract public function getUri($route);
34
35
    /**
36
     * @param $route
37
     *
38
     * @return mixed
39
     */
40
    abstract public function getMethods($route);
41
42
    /**
43
     * @param  \Illuminate\Routing\Route $route
44
     * @param array $bindings
45
     * @param bool $withResponse
46
     *
47
     * @return array
48
     */
49
    public function processRoute($route, $bindings = [], $headers = [], $withResponse = true)
50
    {
51
        $routeDomain = $route->domain();
52
        $routeAction = $route->getAction();
53
        $routeGroup = $this->getRouteGroup($routeAction['uses']);
54
        $routeDescription = $this->getRouteDescription($routeAction['uses']);
55
        $showresponse = null;
56
57
        // set correct route domain
58
        $headers[] = "HTTP_HOST: {$routeDomain}";
59
        $headers[] = "SERVER_NAME: {$routeDomain}";
60
61
        $response = null;
62
        $docblockResponse = $this->getDocblockResponse($routeDescription['tags']);
63
        if ($docblockResponse) {
64
            // we have a response from the docblock ( @response )
65
            $response = $docblockResponse;
66
            $showresponse = true;
67
        }
68
        if (! $response) {
69
            $transformerResponse = $this->getTransformerResponse($routeDescription['tags']);
70
            if ($transformerResponse) {
71
                // we have a transformer response from the docblock ( @transformer || @transformercollection )
72
                $response = $transformerResponse;
73
                $showresponse = true;
74
            }
75
        }
76
        if (! $response && $withResponse) {
77
            try {
78
                $response = $this->getRouteResponse($route, $bindings, $headers);
79
            } catch (\Exception $e) {
80
                dump("Couldn't get response for route: ".implode(',', $this->getMethods($route)).'] '.$route->uri().'', $e->getMessage());
81
            }
82
        }
83
84
        $content = $this->getResponseContent($response);
85
86
        return $this->getParameters([
87
            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
88
            'resource' => $routeGroup,
89
            'title' => $routeDescription['short'],
90
            'description' => $routeDescription['long'],
91
            'methods' => $this->getMethods($route),
92
            'uri' => $this->getUri($route),
93
            'parameters' => [],
94
            'response' => $content,
95
            'showresponse' => $showresponse,
96
        ], $routeAction, $bindings);
97
    }
98
99
    /**
100
     * Prepares / Disables route middlewares.
101
     *
102
     * @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...
103
     *
104
     * @return  void
105
     */
106
    abstract public function prepareMiddleware($enable = false);
107
108
    /**
109
     * Get the response from the docblock if available.
110
     *
111
     * @param array $tags
112
     *
113
     * @return mixed
114
     */
115
    protected function getDocblockResponse($tags)
116
    {
117
        $responseTags = array_filter($tags, function ($tag) {
118
            if (! ($tag instanceof Tag)) {
119
                return false;
120
            }
121
122
            return \strtolower($tag->getName()) == 'response';
123
        });
124
        if (empty($responseTags)) {
125
            return;
126
        }
127
        $responseTag = \array_first($responseTags);
128
129
        return \response(json_encode($responseTag->getContent()), 200, ['Content-Type' => 'application/json']);
130
    }
131
132
    /**
133
     * @param array $routeData
134
     * @param array $routeAction
135
     * @param array $bindings
136
     *
137
     * @return mixed
138
     */
139
    protected function getParameters($routeData, $routeAction, $bindings)
140
    {
141
        $rules = $this->simplifyRules($this->getRouteRules($routeData['methods'], $routeAction['uses'], $bindings));
142
143
        foreach ($rules as $attribute => $ruleset) {
144
            $attributeData = [
145
                'required' => false,
146
                'type' => null,
147
                'default' => '',
148
                'value' => '',
149
                'description' => [],
150
            ];
151
            foreach ($ruleset as $rule) {
152
                $this->parseRule($rule, $attribute, $attributeData, $routeData['id'], $routeData);
153
            }
154
            $routeData['parameters'][$attribute] = $attributeData;
155
        }
156
157
        return $routeData;
158
    }
159
160
    /**
161
     * Format the validation rules as plain array.
162
     *
163
     * @param array $rules
164
     *
165
     * @return array
166
     */
167
    protected function simplifyRules($rules)
168
    {
169
        $simplifiedRules = Validator::make([], $rules)->getRules();
170
171
        if (count($simplifiedRules) === 0) {
172
            return $simplifiedRules;
173
        }
174
175
        $values = collect($simplifiedRules)
176
            ->filter(function ($values) {
177
                return in_array('array', $values);
178
            })->map(function ($val, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $val is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
179
                return [''];
180
            })->all();
181
182
        return Validator::make($values, $rules)->getRules();
183
    }
184
185
    /**
186
     * @param  $route
187
     * @param  $bindings
188
     * @param  $headers
189
     *
190
     * @return \Illuminate\Http\Response
191
     */
192
    protected function getRouteResponse($route, $bindings, $headers = [])
193
    {
194
        $uri = $this->addRouteModelBindings($route, $bindings);
195
196
        $methods = $this->getMethods($route);
197
198
        // Split headers into key - value pairs
199
        $headers = collect($headers)->map(function ($value) {
200
            $split = explode(':', $value); // explode to get key + values
201
            $key = array_shift($split); // extract the key and keep the values in the array
202
            $value = implode(':', $split); // implode values into string again
203
204
            return [trim($key) => trim($value)];
205
        })->collapse()->toArray();
206
207
        //Changes url with parameters like /users/{user} to /users/1
208
        $uri = preg_replace('/{(.*?)}/', 1, $uri); // 1 is the default value for route parameters
209
210
        return $this->callRoute(array_shift($methods), $uri, [], [], [], $headers);
0 ignored issues
show
Bug introduced by
It seems like $uri defined by preg_replace('/{(.*?)}/', 1, $uri) on line 208 can also be of type array<integer,string>; however, Mpociot\ApiDoc\Generator...tGenerator::callRoute() does only seem to accept string, 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...
211
    }
212
213
    /**
214
     * @param $route
215
     * @param array $bindings
216
     *
217
     * @return mixed
218
     */
219
    protected function addRouteModelBindings($route, $bindings)
220
    {
221
        $uri = $this->getUri($route);
222
        foreach ($bindings as $model => $id) {
223
            $uri = str_replace('{'.$model.'}', $id, $uri);
224
            $uri = str_replace('{'.$model.'?}', $id, $uri);
225
        }
226
227
        return $uri;
228
    }
229
230
    /**
231
     * @param  \Illuminate\Routing\Route  $route
232
     *
233
     * @return array
234
     */
235
    protected function getRouteDescription($route)
236
    {
237
        list($class, $method) = explode('@', $route);
238
        $reflection = new ReflectionClass($class);
239
        $reflectionMethod = $reflection->getMethod($method);
240
241
        $comment = $reflectionMethod->getDocComment();
242
        $phpdoc = new DocBlock($comment);
243
244
        return [
245
            'short' => $phpdoc->getShortDescription(),
246
            'long' => $phpdoc->getLongDescription()->getContents(),
247
            'tags' => $phpdoc->getTags(),
248
        ];
249
    }
250
251
    /**
252
     * @param  string  $route
253
     *
254
     * @return string
255
     */
256
    protected function getRouteGroup($route)
257
    {
258
        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...
259
        $reflection = new ReflectionClass($class);
260
        $comment = $reflection->getDocComment();
261
        if ($comment) {
262
            $phpdoc = new DocBlock($comment);
263
            foreach ($phpdoc->getTags() as $tag) {
264
                if ($tag->getName() === 'resource') {
265
                    return $tag->getContent();
266
                }
267
            }
268
        }
269
270
        return 'general';
271
    }
272
273
    /**
274
     * @param  array $routeMethods
275
     * @param  string $routeAction
276
     * @param  array $bindings
277
     *
278
     * @return array
279
     */
280
    protected function getRouteRules(array $routeMethods, $routeAction, $bindings)
281
    {
282
        list($class, $method) = explode('@', $routeAction);
283
        $reflection = new ReflectionClass($class);
284
        $reflectionMethod = $reflection->getMethod($method);
285
286
        foreach ($reflectionMethod->getParameters() as $parameter) {
287
            $parameterType = $parameter->getClass();
288
            if (! is_null($parameterType) && class_exists($parameterType->name)) {
289
                $className = $parameterType->name;
290
291
                if (is_subclass_of($className, FormRequest::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Illuminate\Foundation\Http\FormRequest::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
292
                    /** @var FormRequest $formRequest */
293
                    $formRequest = new $className;
294
                    // Add route parameter bindings
295
                    $formRequest->setContainer(app());
296
                    $formRequest->request->add($bindings);
297
                    $formRequest->query->add($bindings);
298
                    $formRequest->setMethod($routeMethods[0]);
299
300
                    if (method_exists($formRequest, 'validator')) {
301
                        $factory = app(ValidationFactory::class);
302
303
                        return call_user_func_array([$formRequest, 'validator'], [$factory])
304
                            ->getRules();
305
                    } else {
306
                        return call_user_func_array([$formRequest, 'rules'], []);
307
                    }
308
                }
309
            }
310
        }
311
312
        return [];
313
    }
314
315
    /**
316
     * @param  array  $arr
317
     * @param  string  $first
318
     * @param  string  $last
319
     *
320
     * @return string
321
     */
322
    protected function fancyImplode($arr, $first, $last)
323
    {
324
        $arr = array_map(function ($value) {
325
            return '`'.$value.'`';
326
        }, $arr);
327
        array_push($arr, implode($last, array_splice($arr, -2)));
328
329
        return implode($first, $arr);
330
    }
331
332
    protected function splitValuePairs($parameters, $first = 'is ', $last = 'or ')
333
    {
334
        $attribute = '';
335
        collect($parameters)->map(function ($item, $key) use (&$attribute, $first, $last) {
336
            $attribute .= '`'.$item.'` ';
337
            if (($key + 1) % 2 === 0) {
338
                $attribute .= $last;
339
            } else {
340
                $attribute .= $first;
341
            }
342
        });
343
        $attribute = rtrim($attribute, $last);
344
345
        return $attribute;
346
    }
347
348
    /**
349
     * @param  string  $rule
350
     * @param  string  $ruleName
351
     * @param  array  $attributeData
352
     * @param  int  $seed
353
     *
354
     * @return void
355
     */
356
    protected function parseRule($rule, $ruleName, &$attributeData, $seed, $routeData)
357
    {
358
        $faker = Factory::create();
359
        $faker->seed(crc32($seed));
360
361
        $parsedRule = $this->parseStringRule($rule);
362
        $parsedRule[0] = $this->normalizeRule($parsedRule[0]);
363
        list($rule, $parameters) = $parsedRule;
364
365
        switch ($rule) {
366
            case 'required':
367
                $attributeData['required'] = true;
368
                break;
369
            case 'accepted':
370
                $attributeData['required'] = true;
371
                $attributeData['type'] = 'boolean';
372
                $attributeData['value'] = true;
373
                break;
374 View Code Duplication
            case 'after':
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...
375
                $attributeData['type'] = 'date';
376
                $format = isset($attributeData['format']) ? $attributeData['format'] : DATE_RFC850;
377
378
                if (strtotime($parameters[0]) === false) {
379
                    // the `after` date refers to another parameter in the request
380
                    $paramName = $parameters[0];
381
                    $attributeData['description'][] = Description::parse($rule)->with($paramName)->getDescription();
382
                    $attributeData['value'] = date($format, strtotime('+1 day', strtotime($routeData['parameters'][$paramName]['value'])));
383
                } else {
384
                    $attributeData['description'][] = Description::parse($rule)->with(date($format, strtotime($parameters[0])))->getDescription();
385
                    $attributeData['value'] = date($format, strtotime('+1 day', strtotime($parameters[0])));
386
                }
387
                break;
388 View Code Duplication
            case 'alpha':
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...
389
                $attributeData['description'][] = Description::parse($rule)->getDescription();
390
                $attributeData['value'] = $faker->word;
391
                break;
392
            case 'alpha_dash':
393
                $attributeData['description'][] = Description::parse($rule)->getDescription();
394
                break;
395
            case 'alpha_num':
396
                $attributeData['description'][] = Description::parse($rule)->getDescription();
397
                break;
398 View Code Duplication
            case 'in':
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...
399
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
400
                $attributeData['value'] = $faker->randomElement($parameters);
401
                break;
402 View Code Duplication
            case 'not_in':
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...
403
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
404
                $attributeData['value'] = $faker->word;
405
                break;
406 View Code Duplication
            case 'min':
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...
407
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
408
                if (Arr::get($attributeData, 'type') === 'numeric' || Arr::get($attributeData, 'type') === 'integer') {
409
                    $attributeData['value'] = $faker->numberBetween($parameters[0]);
410
                }
411
                break;
412 View Code Duplication
            case 'max':
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...
413
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
414
                if (Arr::get($attributeData, 'type') === 'numeric' || Arr::get($attributeData, 'type') === 'integer') {
415
                    $attributeData['value'] = $faker->numberBetween(0, $parameters[0]);
416
                }
417
                break;
418 View Code Duplication
            case 'between':
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...
419
                if (! isset($attributeData['type'])) {
420
                    $attributeData['type'] = 'numeric';
421
                }
422
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
423
                $attributeData['value'] = $faker->numberBetween($parameters[0], $parameters[1]);
424
                break;
425 View Code Duplication
            case 'before':
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...
426
                $attributeData['type'] = 'date';
427
                $format = isset($attributeData['format']) ? $attributeData['format'] : DATE_RFC850;
428
429
                if (strtotime($parameters[0]) === false) {
430
                    // the `before` date refers to another parameter in the request
431
                    $paramName = $parameters[0];
432
                    $attributeData['description'][] = Description::parse($rule)->with($paramName)->getDescription();
433
                    $attributeData['value'] = date($format, strtotime('-1 day', strtotime($routeData['parameters'][$paramName]['value'])));
434
                } else {
435
                    $attributeData['description'][] = Description::parse($rule)->with(date($format, strtotime($parameters[0])))->getDescription();
436
                    $attributeData['value'] = date($format, strtotime('-1 day', strtotime($parameters[0])));
437
                }
438
                break;
439 View Code Duplication
            case 'date_format':
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...
440
                $attributeData['type'] = 'date';
441
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
442
                $attributeData['format'] = $parameters[0];
443
                $attributeData['value'] = date($attributeData['format']);
444
                break;
445
            case 'different':
446
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
447
                break;
448
            case 'digits':
449
                $attributeData['type'] = 'numeric';
450
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
451
                $attributeData['value'] = ($parameters[0] < 9) ? $faker->randomNumber($parameters[0], true) : substr(mt_rand(100000000, mt_getrandmax()), 0, $parameters[0]);
452
                break;
453
            case 'digits_between':
454
                $attributeData['type'] = 'numeric';
455
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
456
                break;
457 View Code Duplication
            case 'file':
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...
458
                $attributeData['type'] = 'file';
459
                $attributeData['description'][] = Description::parse($rule)->getDescription();
460
                break;
461 View Code Duplication
            case 'image':
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...
462
                $attributeData['type'] = 'image';
463
                $attributeData['description'][] = Description::parse($rule)->getDescription();
464
                break;
465
            case 'json':
466
                $attributeData['type'] = 'string';
467
                $attributeData['description'][] = Description::parse($rule)->getDescription();
468
                $attributeData['value'] = json_encode(['foo', 'bar', 'baz']);
469
                break;
470
            case 'mimetypes':
471 View Code Duplication
            case 'mimes':
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...
472
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
473
                break;
474 View Code Duplication
            case 'required_if':
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...
475
                $attributeData['description'][] = Description::parse($rule)->with($this->splitValuePairs($parameters))->getDescription();
476
                break;
477 View Code Duplication
            case 'required_unless':
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...
478
                $attributeData['description'][] = Description::parse($rule)->with($this->splitValuePairs($parameters))->getDescription();
479
                break;
480 View Code Duplication
            case 'required_with':
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...
481
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
482
                break;
483 View Code Duplication
            case 'required_with_all':
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...
484
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' and '))->getDescription();
485
                break;
486 View Code Duplication
            case 'required_without':
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...
487
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
488
                break;
489 View Code Duplication
            case 'required_without_all':
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...
490
                $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' and '))->getDescription();
491
                break;
492
            case 'same':
493
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
494
                break;
495
            case 'size':
496
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
497
                break;
498 View Code Duplication
            case 'timezone':
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...
499
                $attributeData['description'][] = Description::parse($rule)->getDescription();
500
                $attributeData['value'] = $faker->timezone;
501
                break;
502
            case 'exists':
503
                $fieldName = isset($parameters[1]) ? $parameters[1] : $ruleName;
504
                $attributeData['description'][] = Description::parse($rule)->with([Str::singular($parameters[0]), $fieldName])->getDescription();
505
                break;
506
            case 'active_url':
507
                $attributeData['type'] = 'url';
508
                $attributeData['value'] = $faker->url;
509
                break;
510
            case 'regex':
511
                $attributeData['type'] = 'string';
512
                $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
513
                break;
514
            case 'boolean':
515
                $attributeData['value'] = true;
516
                $attributeData['type'] = $rule;
517
                break;
518
            case 'array':
519
                $attributeData['value'] = $faker->word;
520
                $attributeData['type'] = $rule;
521
                break;
522
            case 'date':
523
                $attributeData['value'] = $faker->date();
524
                $attributeData['type'] = $rule;
525
                break;
526
            case 'email':
527
                $attributeData['value'] = $faker->safeEmail;
528
                $attributeData['type'] = $rule;
529
                break;
530
            case 'string':
531
                $attributeData['value'] = $faker->word;
532
                $attributeData['type'] = $rule;
533
                break;
534
            case 'integer':
535
                $attributeData['value'] = $faker->randomNumber();
536
                $attributeData['type'] = $rule;
537
                break;
538
            case 'numeric':
539
                $attributeData['value'] = $faker->randomNumber();
540
                $attributeData['type'] = $rule;
541
                break;
542
            case 'url':
543
                $attributeData['value'] = $faker->url;
544
                $attributeData['type'] = $rule;
545
                break;
546
            case 'ip':
547
                $attributeData['value'] = $faker->ipv4;
548
                $attributeData['type'] = $rule;
549
                break;
550
            default:
551
                $unknownRuleDescription = Description::parse($rule)->getDescription();
552
                if ($unknownRuleDescription) {
553
                    $attributeData['description'][] = $unknownRuleDescription;
554
                }
555
                break;
556
        }
557
558
        if ($attributeData['value'] === '') {
559
            $attributeData['value'] = $faker->word;
560
        }
561
562
        if (is_null($attributeData['type'])) {
563
            $attributeData['type'] = 'string';
564
        }
565
    }
566
567
    /**
568
     * Call the given URI and return the Response.
569
     *
570
     * @param  string  $method
571
     * @param  string  $uri
572
     * @param  array  $parameters
573
     * @param  array  $cookies
574
     * @param  array  $files
575
     * @param  array  $server
576
     * @param  string  $content
577
     *
578
     * @return \Illuminate\Http\Response
579
     */
580
    abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
581
582
    /**
583
     * Transform headers array to array of $_SERVER vars with HTTP_* format.
584
     *
585
     * @param  array  $headers
586
     *
587
     * @return array
588
     */
589
    protected function transformHeadersToServerVars(array $headers)
590
    {
591
        $server = [];
592
        $prefix = 'HTTP_';
593
594
        foreach ($headers as $name => $value) {
595
            $name = strtr(strtoupper($name), '-', '_');
596
597
            if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
598
                $name = $prefix.$name;
599
            }
600
601
            $server[$name] = $value;
602
        }
603
604
        return $server;
605
    }
606
607
    /**
608
     * Parse a string based rule.
609
     *
610
     * @param  string  $rules
611
     *
612
     * @return array
613
     */
614
    protected function parseStringRule($rules)
615
    {
616
        $parameters = [];
617
618
        // The format for specifying validation rules and parameters follows an
619
        // easy {rule}:{parameters} formatting convention. For instance the
620
        // rule "Max:3" states that the value may only be three letters.
621
        if (strpos($rules, ':') !== false) {
622
            list($rules, $parameter) = explode(':', $rules, 2);
623
624
            $parameters = $this->parseParameters($rules, $parameter);
625
        }
626
627
        return [strtolower(trim($rules)), $parameters];
628
    }
629
630
    /**
631
     * Parse a parameter list.
632
     *
633
     * @param  string  $rule
634
     * @param  string  $parameter
635
     *
636
     * @return array
637
     */
638
    protected function parseParameters($rule, $parameter)
639
    {
640
        if (strtolower($rule) === 'regex') {
641
            return [$parameter];
642
        }
643
644
        return str_getcsv($parameter);
645
    }
646
647
    /**
648
     * Normalizes a rule so that we can accept short types.
649
     *
650
     * @param  string $rule
651
     *
652
     * @return string
653
     */
654
    protected function normalizeRule($rule)
655
    {
656
        switch ($rule) {
657
            case 'int':
658
                return 'integer';
659
            case 'bool':
660
                return 'boolean';
661
            default:
662
                return $rule;
663
        }
664
    }
665
666
    /**
667
     * @param $response
668
     *
669
     * @return mixed
670
     */
671
    private function getResponseContent($response)
672
    {
673
        if (empty($response)) {
674
            return '';
675
        }
676
        if ($response->headers->get('Content-Type') === 'application/json') {
677
            $content = json_decode($response->getContent(), JSON_PRETTY_PRINT);
678
        } else {
679
            $content = $response->getContent();
680
        }
681
682
        return $content;
683
    }
684
685
    /**
686
     * Get a response from the transformer tags.
687
     *
688
     * @param array $tags
689
     *
690
     * @return mixed
691
     */
692
    protected function getTransformerResponse($tags)
693
    {
694
        try {
695
            $transFormerTags = array_filter($tags, function ($tag) {
696
                if (! ($tag instanceof Tag)) {
697
                    return false;
698
                }
699
700
                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
701
            });
702
            if (empty($transFormerTags)) {
703
                // we didn't have any of the tags so goodbye
704
                return false;
705
            }
706
707
            $modelTag = array_first(array_filter($tags, function ($tag) {
708
                if (! ($tag instanceof Tag)) {
709
                    return false;
710
                }
711
712
                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
713
            }));
714
            $tag = \array_first($transFormerTags);
715
            $transformer = $tag->getContent();
716
            if (! \class_exists($transformer)) {
717
                // if we can't find the transformer we can't generate a response
718
                return;
719
            }
720
            $demoData = [];
721
722
            $reflection = new ReflectionClass($transformer);
723
            $method = $reflection->getMethod('transform');
724
            $parameter = \array_first($method->getParameters());
725
            $type = null;
726
            if ($modelTag) {
727
                $type = $modelTag->getContent();
728
            }
729
            if (version_compare(PHP_VERSION, '7.0.0') >= 0 && \is_null($type)) {
730
                // we can only get the type with reflection for PHP 7
731
                if ($parameter->hasType() &&
732
                    ! $parameter->getType()->isBuiltin() &&
733
                    \class_exists((string) $parameter->getType())) {
734
                    //we have a type
735
                    $type = (string) $parameter->getType();
736
                }
737
            }
738
            if ($type) {
739
                // we have a class so we try to create an instance
740
                $demoData = new $type;
741
                try {
742
                    // try a factory
743
                    $demoData = \factory($type)->make();
744
                } catch (\Exception $e) {
745
                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
746
                        // we can't use a factory but can try to get one from the database
747
                        try {
748
                            // check if we can find one
749
                            $newDemoData = $type::first();
750
                            if ($newDemoData) {
751
                                $demoData = $newDemoData;
752
                            }
753
                        } catch (\Exception $e) {
754
                            // do nothing
755
                        }
756
                    }
757
                }
758
            }
759
760
            $fractal = new Manager();
761
            $resource = [];
762
            if ($tag->getName() == 'transformer') {
763
                // just one
764
                $resource = new Item($demoData, new $transformer);
765
            }
766
            if ($tag->getName() == 'transformercollection') {
767
                // a collection
768
                $resource = new Collection([$demoData, $demoData], new $transformer);
769
            }
770
771
            return \response($fractal->createData($resource)->toJson());
0 ignored issues
show
Bug introduced by
It seems like $resource defined by array() on line 761 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...
772
        } catch (\Exception $e) {
773
            // it isn't possible to parse the transformer
774
            return;
775
        }
776
    }
777
}
778