Completed
Push — master ( ad721e...9c02d3 )
by Garveen
04:01
created

Base   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 226
Duplicated Lines 4.42 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 92.91%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 10
loc 226
ccs 118
cts 127
cp 0.9291
rs 8.6
c 1
b 0
f 0
wmc 37
lcom 1
cbo 5

9 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 4 1
A init() 0 8 1
B convertRequest() 0 15 8
C prepareKernel() 10 43 8
D handleRequest() 0 52 9
A onPsrRequest() 0 9 2
B clean() 0 22 5
A getApp() 0 7 2
A createApp() 0 23 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace Laravoole;
3
4
use Exception;
5
use ErrorException;
6
7
use swoole_http_request;
8
9
use Laravoole\Illuminate\Application;
10
use Laravoole\Illuminate\Request as IlluminateRequest;
11
12
use Illuminate\Support\Facades\Facade;
13
use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
14
use Psr\Http\Message\ServerRequestInterface;
15
16
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
17
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
18
19
abstract class Base
20
{
21
22
    protected $root_dir;
23
24
    protected $pid_file;
25
26
    public $base_config;
27
28
    public $handler_config;
29
30
    public $wrapper_config;
31
32
    protected $kernel;
33
34
    protected $tmp_autoloader;
35
36
    protected $app;
37
38
    protected $server;
39
40
    protected $diactorosFactory;
41
42
    /**
43
     * For wrappers' events.
44
     * @var array
45
     */
46
    protected $callbacks = [];
47
48
    /**
49
     * Start the server
50
     * @codeCoverageIgnore
51
     */
52
    public function start()
53
    {
54
        throw new Exception(__CLASS__ . "::start MUST be implemented", 1);
55
    }
56
57 20
    final public function init(array $configs)
58
    {
59 20
        $this->pid_file = $configs['pid_file'];
60 20
        $this->root_dir = $configs['root_dir'];
61 20
        $this->base_config = $configs['base_config'];
62 20
        $this->handler_config = $configs['handler_config'];
63 20
        $this->wrapper_config = $configs['wrapper_config'];
64 20
    }
65
66 20
    public function prepareKernel()
67
    {
68
        // unregister temporary autoloader
69 20
        foreach (spl_autoload_functions() as $function) {
70 20
            spl_autoload_unregister($function);
71 10
        }
72
73 20
        if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
74 20
            require __DIR__ . '/../vendor/autoload.php';
75 10
        } else {
76
            require $this->root_dir . '/bootstrap/autoload.php';
77
        }
78 20 View Code Duplication
        if (isset($this->base_config['callbacks']['bootstraping'])) {
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...
79 20
            foreach ($this->base_config['callbacks']['bootstraping'] as $callback) {
80 20
                $callback($this);
81 10
            }
82 10
        }
83 20
        $this->app = $this->getApp();
84
85 20
        if (isset($this->wrapper_config['environment_path'])) {
86 20
            $this->app->useEnvironmentPath($this->wrapper_config['environment_path']);
87 10
        }
88
89 20
        $this->kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);
90 20
        $virus = function () {
91
            // Insert bofore BootProviders
92 20
            array_splice($this->bootstrappers, -1, 0, [\Illuminate\Foundation\Bootstrap\SetRequestForConsole::class]);
0 ignored issues
show
Bug introduced by
The property bootstrappers does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
93 20
        };
94 20
        $virus = \Closure::bind($virus, $this->kernel, $this->kernel);
95 20
        $virus();
96
97 20
        $this->kernel->bootstrap();
98 20
        chdir(public_path());
99 20
        $config = $this->app['config']->get('laravoole.base_config', []);
100 20
        $this->app['config']->set('laravoole.base_config', array_merge($config, $this->base_config));
101
102 20 View Code Duplication
        if (isset($this->base_config['callbacks']['bootstraped'])) {
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...
103 20
            foreach ($this->base_config['callbacks']['bootstraped'] as $callback) {
104 20
                $callback($this);
105 10
            }
106 10
        }
107 20
        $this->events = $this->app['events'];
0 ignored issues
show
Bug introduced by
The property events does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
108 20
    }
109
110 20
    public function handleRequest($request, IlluminateRequest $illuminate_request = null)
111
    {
112 20
        clearstatcache();
113
114 20
        $kernel = $this->kernel;
115
116
        try {
117
118 20
            ob_start();
119
120 20
            if (!$illuminate_request) {
121 20
                if ($request instanceof ServerRequestInterface) {
122 8
                    $request = (new HttpFoundationFactory)->createRequest($request);
123 8
                    $illuminate_request = IlluminateRequest::createFromBase($request);
124 10
                } elseif ($request instanceof swoole_http_request) {
0 ignored issues
show
Bug introduced by
The class swoole_http_request does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
125 8
                    $illuminate_request = $this->convertRequest($request);
126 4
                } else {
127 11
                    $illuminate_request = IlluminateRequest::createFromBase($request);
128
                }
129 10
            }
130
131 20
            $this->events->fire('laravoole.requesting', [$illuminate_request]);
132
133 20
            $illuminate_response = $kernel->handle($illuminate_request);
134
135 20
            $content = $illuminate_response->getContent();
136
137 20
            if (strlen($content) === 0 && ob_get_length() > 0) {
138
                $illuminate_response->setContent(ob_get_contents());
139
            }
140
141 20
            ob_end_clean();
142
143 10
        } catch (\Exception $e) {
144
            echo '[ERR] ' . $e->getFile() . '(' . $e->getLine() . '): ' . $e->getMessage() . PHP_EOL;
145
            echo $e->getTraceAsString() . PHP_EOL;
146
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
147
            echo '[ERR] ' . $e->getFile() . '(' . $e->getLine() . '): ' . $e->getMessage() . PHP_EOL;
148
            echo $e->getTraceAsString() . PHP_EOL;
149 20
        } finally {
150 20
            if (isset($illuminate_response)) {
151 20
                $kernel->terminate($illuminate_request, $illuminate_response);
152 10
            }
153 20
            $this->events->fire('laravoole.requested', [$illuminate_request, $illuminate_response]);
0 ignored issues
show
Bug introduced by
The variable $illuminate_response does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
154
155 20
            $this->clean($illuminate_request);
0 ignored issues
show
Documentation introduced by
$illuminate_request is of type null|object, but the function expects a object<Laravoole\Illuminate\Request>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
156
157
        }
158
159 20
        return $illuminate_response;
160
161
    }
162
163 8
    public function onPsrRequest(ServerRequestInterface $psrRequest)
164
    {
165 8
        $illuminate_response = $this->handleRequest($psrRequest);
166 8
        if (!$this->diactorosFactory) {
167 8
            $this->diactorosFactory = new DiactorosFactory;
168 4
        }
169 8
        return $this->diactorosFactory->createResponse($illuminate_response);
170
171
    }
172
173 8
    protected function convertRequest($request, $classname = IlluminateRequest::class)
174
    {
175
176 8
        $get = isset($request->get) ? $request->get : [];
177 8
        $post = isset($request->post) ? $request->post : [];
178 8
        $cookie = isset($request->cookie) ? $request->cookie : [];
179 8
        $server = isset($request->server) ? $request->server : [];
180 8
        $header = isset($request->header) ? $request->header : [];
0 ignored issues
show
Unused Code introduced by
$header is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
181 8
        $files = isset($request->files) ? $request->files : [];
182
        // $attr = isset($request->files) ? $request->files : [];
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
183
184 8
        $content = $request->rawContent() ?: null;
185
186 8
        return new $classname($get, $post, []/* attributes */, $cookie, $files, $server, $content);
187
    }
188
189 20
    protected function clean(IlluminateRequest $request)
190
    {
191 20
        if ($request->hasSession()) {
192 20
            $session = $request->getSession();
193 20
            if (is_callable([$session, 'clear'])) {
194
                $session->clear(); // @codeCoverageIgnore
195 5
            } else {
196 15
                $session->flush();
0 ignored issues
show
Bug introduced by
The method flush() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

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...
197
            }
198 10
        }
199
200
        // Clean laravel cookie queue
201 20
        $cookies = $this->app->make(CookieJar::class);
202 20
        foreach ($cookies->getQueuedCookies() as $name => $cookie) {
203
            $cookies->unqueue($name);
204 10
        }
205
206 20
        if ($this->app->isProviderLoaded(\Illuminate\Auth\AuthServiceProvider::class)) {
207 20
            $this->app->register(\Illuminate\Auth\AuthServiceProvider::class, [], true);
208 20
            Facade::clearResolvedInstance('auth');
209 10
        }
210 20
    }
211
212 20
    public function getApp()
213
    {
214 20
        if (!$this->app) {
215 20
            $this->app = $this->createApp();
216 10
        }
217 20
        return $this->app;
218
    }
219
220 20
    protected function createApp()
221
    {
222 20
        $app = new Application($this->root_dir);
223 20
        $rootNamespace = $app->getNamespace();
224 20
        $rootNamespace = trim($rootNamespace, '\\');
225
226 20
        $app->singleton(
227 20
            \Illuminate\Contracts\Http\Kernel::class,
228 20
            "\\{$rootNamespace}\\Http\\Kernel"
229 10
        );
230
231 20
        $app->singleton(
232 20
            \Illuminate\Contracts\Console\Kernel::class,
233 20
            "\\{$rootNamespace}\\Console\\Kernel"
234 10
        );
235
236 20
        $app->singleton(
237 20
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
238 20
            "\\{$rootNamespace}\\Exceptions\\Handler"
239 10
        );
240
241 20
        return $app;
242
    }
243
244
}
245