Completed
Pull Request — master (#318)
by
unknown
11:06
created

LaravelGenerator::processRoute()   B

Complexity

Conditions 7
Paths 25

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 8.1138
c 0
b 0
f 0
cc 7
nc 25
nop 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A LaravelGenerator::callRoute() 0 19 1

How to fix   Long Method   

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 Exception;
6
use ReflectionClass;
7
use League\Fractal\Manager;
8
use Illuminate\Routing\Route;
9
use League\Fractal\Resource\Item;
10
use Illuminate\Support\Facades\App;
11
use Mpociot\Reflection\DocBlock\Tag;
12
use Illuminate\Support\Facades\Request;
13
use League\Fractal\Resource\Collection;
14
15
class LaravelGenerator extends AbstractGenerator
16
{
17
    /**
18
     * @param Route $route
19
     *
20
     * @return mixed
21
     */
22
    public function getDomain($route)
23
    {
24
        return $route->domain();
25
    }
26
27
    /**
28
     * @param Route $route
29
     *
30
     * @return mixed
31
     */
32
    public function getUri($route)
33
    {
34
        if (version_compare(app()->version(), '5.4', '<')) {
35
            return $route->getUri();
0 ignored issues
show
Bug introduced by
The method getUri() does not seem to exist on object<Illuminate\Routing\Route>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
36
        }
37
38
        return $route->uri();
39
    }
40
41
    /**
42
     * @param Route $route
43
     *
44
     * @return mixed
45
     */
46
    public function getMethods($route)
47
    {
48
        if (version_compare(app()->version(), '5.4', '<')) {
49
            $methods = $route->getMethods();
0 ignored issues
show
Bug introduced by
The method getMethods() does not exist on Illuminate\Routing\Route. Did you maybe mean methods()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
50
        } else {
51
            $methods = $route->methods();
52
        }
53
54
        return array_diff($methods, ['HEAD']);
55
    }
56
57
    /**
58
     * Prepares / Disables route middlewares.
59
     *
60
     * @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...
61
     *
62
     * @return  void
63
     */
64
    public function prepareMiddleware($enable = true)
65
    {
66
        App::instance('middleware.disable', ! $enable);
0 ignored issues
show
Bug introduced by
The method instance() does not exist on Illuminate\Support\Facades\App. Did you maybe mean clearResolvedInstance()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
67
    }
68
69
    /**
70
     * Call the given URI and return the Response.
71
     *
72
     * @param  string  $method
73
     * @param  string  $uri
74
     * @param  array  $parameters
75
     * @param  array  $cookies
76
     * @param  array  $files
77
     * @param  array  $server
78
     * @param  string  $content
79
     *
80
     * @return \Illuminate\Http\Response
81
     */
82
    public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
83
    {
84
        $server = collect([
85
            'CONTENT_TYPE' => 'application/json',
86
            'Accept' => 'application/json',
87
        ])->merge($server)->toArray();
88
89
        $request = Request::create(
0 ignored issues
show
Bug introduced by
The method create() does not exist on Illuminate\Support\Facades\Request. Did you maybe mean createFreshMockInstance()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
90
            $uri, $method, $parameters,
91
            $cookies, $files, $this->transformHeadersToServerVars($server), $content
92
        );
93
94
        $kernel = App::make('Illuminate\Contracts\Http\Kernel');
95
        $response = $kernel->handle($request);
96
97
        $kernel->terminate($request, $response);
98
99
        return $response;
100
    }
101
102
    /**
103
     * Get a response from the transformer tags.
104
     *
105
     * @param array $tags
106
     *
107
     * @return mixed
108
     */
109
    protected function getTransformerResponse($tags)
110
    {
111
        try {
112
            $transFormerTags = array_filter($tags, function ($tag) {
113
                if (! ($tag instanceof Tag)) {
114
                    return false;
115
                }
116
117
                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
118
            });
119
            if (empty($transFormerTags)) {
120
                // we didn't have any of the tags so goodbye
121
                return false;
122
            }
123
124
            $modelTag = array_first(array_filter($tags, function ($tag) {
125
                if (! ($tag instanceof Tag)) {
126
                    return false;
127
                }
128
129
                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
130
            }));
131
            $tag = \array_first($transFormerTags);
132
            $transformer = $tag->getContent();
133
            if (! \class_exists($transformer)) {
134
                // if we can't find the transformer we can't generate a response
135
                return;
136
            }
137
            $demoData = [];
138
139
            $reflection = new ReflectionClass($transformer);
140
            $method = $reflection->getMethod('transform');
141
            $parameter = \array_first($method->getParameters());
142
            $type = null;
143
            if ($modelTag) {
144
                $type = $modelTag->getContent();
145
            }
146
            if (version_compare(PHP_VERSION, '7.0.0') >= 0 && \is_null($type)) {
147
                // we can only get the type with reflection for PHP 7
148
                if ($parameter->hasType() &&
149
                ! $parameter->getType()->isBuiltin() &&
150
                \class_exists((string) $parameter->getType())) {
151
                    //we have a type
152
                    $type = (string) $parameter->getType();
153
                }
154
            }
155
            if ($type) {
156
                // we have a class so we try to create an instance
157
                $demoData = new $type;
158
                try {
159
                    // try a factory
160
                    $demoData = \factory($type)->make();
161
                } catch (\Exception $e) {
162
                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
163
                        // we can't use a factory but can try to get one from the database
164
                        try {
165
                            // check if we can find one
166
                            $newDemoData = $type::first();
167
                            if ($newDemoData) {
168
                                $demoData = $newDemoData;
169
                            }
170
                        } catch (\Exception $e) {
171
                            // do nothing
172
                        }
173
                    }
174
                }
175
            }
176
177
            $fractal = new Manager();
178
            $resource = [];
179
            if ($tag->getName() == 'transformer') {
180
                // just one
181
                $resource = new Item($demoData, new $transformer);
182
            }
183
            if ($tag->getName() == 'transformercollection') {
184
                // a collection
185
                $resource = new Collection([$demoData, $demoData], new $transformer);
186
            }
187
188
            return \response($fractal->createData($resource)->toJson());
0 ignored issues
show
Bug introduced by
It seems like $resource defined by array() on line 178 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...
189
        } catch (\Exception $e) {
190
            // it isn't possible to parse the transformer
191
            return;
192
        }
193
    }
194
}
195