Base   B
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 229
Duplicated Lines 4.37 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 92.91%

Importance

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

9 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 4 1
A init() 0 8 1
D prepareKernel() 10 46 10
D handleRequest() 0 52 9
A onPsrRequest() 0 9 2
B convertRequest() 0 15 8
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
        } elseif (file_exists(__DIR__.'/../../../autoload.php')) {
76
            require __DIR__ . '/../../../autoload.php';
77
        } elseif (file_exists($this->root_dir . '/bootstrap/autoload.php')) {
78 20
            //as of laravel>=5.5, optimize command has been deprecated
79 20
            require $this->root_dir . '/bootstrap/autoload.php';
80 20
        }
81 10 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...
82 10
            foreach ($this->base_config['callbacks']['bootstraping'] as $callback) {
83 20
                $callback($this);
84
            }
85 20
        }
86 20
        $this->app = $this->getApp();
87 10
88
        if (isset($this->wrapper_config['environment_path'])) {
89 20
            $this->app->useEnvironmentPath($this->wrapper_config['environment_path']);
90 20
        }
91
92 20
        $this->kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);
93 20
        $virus = function () {
94 20
            // Insert bofore BootProviders
95 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...
96
        };
97 20
        $virus = \Closure::bind($virus, $this->kernel, $this->kernel);
98 20
        $virus();
99 20
100 20
        $this->kernel->bootstrap();
101
        chdir(public_path());
102 20
        $config = $this->app['config']->get('laravoole.base_config', []);
103 20
        $this->app['config']->set('laravoole.base_config', array_merge($config, $this->base_config));
104 20
105 10 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...
106 10
            foreach ($this->base_config['callbacks']['bootstraped'] as $callback) {
107 20
                $callback($this);
108 20
            }
109
        }
110 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...
111
    }
112 20
113
    public function handleRequest($request, IlluminateRequest $illuminate_request = null)
114 20
    {
115
        clearstatcache();
116
117
        $kernel = $this->kernel;
118 20
119
        try {
120 20
121 20
            ob_start();
122 8
123 8
            if (!$illuminate_request) {
124 10
                if ($request instanceof ServerRequestInterface) {
125 8
                    $request = (new HttpFoundationFactory)->createRequest($request);
126 4
                    $illuminate_request = IlluminateRequest::createFromBase($request);
127 11
                } 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...
128
                    $illuminate_request = $this->convertRequest($request);
129 10
                } else {
130
                    $illuminate_request = IlluminateRequest::createFromBase($request);
131 20
                }
132
            }
133 20
134
            $this->events->fire('laravoole.requesting', [$illuminate_request]);
135 20
136
            $illuminate_response = $kernel->handle($illuminate_request);
137 20
138
            $content = $illuminate_response->getContent();
139
140
            if (strlen($content) === 0 && ob_get_length() > 0) {
141 20
                $illuminate_response->setContent(ob_get_contents());
142
            }
143 10
144
            ob_end_clean();
145
146
        } catch (\Exception $e) {
147
            echo '[ERR] ' . $e->getFile() . '(' . $e->getLine() . '): ' . $e->getMessage() . PHP_EOL;
148
            echo $e->getTraceAsString() . PHP_EOL;
149 20
        } 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...
150 20
            echo '[ERR] ' . $e->getFile() . '(' . $e->getLine() . '): ' . $e->getMessage() . PHP_EOL;
151 20
            echo $e->getTraceAsString() . PHP_EOL;
152 10
        } finally {
153 20
            if (isset($illuminate_response)) {
154
                $kernel->terminate($illuminate_request, $illuminate_response);
155 20
            }
156
            $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...
157
158
            $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...
159 20
160
        }
161
162
        return $illuminate_response;
163 8
164
    }
165 8
166 8
    public function onPsrRequest(ServerRequestInterface $psrRequest)
167 8
    {
168 4
        $illuminate_response = $this->handleRequest($psrRequest);
169 8
        if (!$this->diactorosFactory) {
170
            $this->diactorosFactory = new DiactorosFactory;
171
        }
172
        return $this->diactorosFactory->createResponse($illuminate_response);
173 8
174
    }
175
176 8
    protected function convertRequest($request, $classname = IlluminateRequest::class)
177 8
    {
178 8
179 8
        $get = isset($request->get) ? $request->get : [];
180 8
        $post = isset($request->post) ? $request->post : [];
181 8
        $cookie = isset($request->cookie) ? $request->cookie : [];
182
        $server = isset($request->server) ? $request->server : [];
183
        $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...
184 8
        $files = isset($request->files) ? $request->files : [];
185
        // $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...
186 8
187
        $content = $request->rawContent() ?: null;
188
189 20
        return new $classname($get, $post, []/* attributes */, $cookie, $files, $server, $content);
190
    }
191 20
192 20
    protected function clean(IlluminateRequest $request)
193 20
    {
194
        if ($request->hasSession()) {
195 5
            $session = $request->getSession();
196 15
            if (is_callable([$session, 'clear'])) {
197
                $session->clear(); // @codeCoverageIgnore
198 10
            } else {
199
                $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...
200
            }
201 20
        }
202 20
203
        // Clean laravel cookie queue
204 10
        $cookies = $this->app->make(CookieJar::class);
205
        foreach ($cookies->getQueuedCookies() as $name => $cookie) {
206 20
            $cookies->unqueue($name);
207 20
        }
208 20
209 10
        if ($this->app->isProviderLoaded(\Illuminate\Auth\AuthServiceProvider::class)) {
210 20
            $this->app->register(\Illuminate\Auth\AuthServiceProvider::class, [], true);
211
            Facade::clearResolvedInstance('auth');
212 20
        }
213
    }
214 20
215 20
    public function getApp()
216 10
    {
217 20
        if (!$this->app) {
218
            $this->app = $this->createApp();
219
        }
220 20
        return $this->app;
221
    }
222 20
223 20
    protected function createApp()
224 20
    {
225
        $app = new Application($this->root_dir);
226 20
        $rootNamespace = $app->getNamespace();
227 20
        $rootNamespace = trim($rootNamespace, '\\');
228 20
229 10
        $app->singleton(
230
            \Illuminate\Contracts\Http\Kernel::class,
231 20
            "\\{$rootNamespace}\\Http\\Kernel"
232 20
        );
233 20
234 10
        $app->singleton(
235
            \Illuminate\Contracts\Console\Kernel::class,
236 20
            "\\{$rootNamespace}\\Console\\Kernel"
237 20
        );
238 20
239 10
        $app->singleton(
240
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
241 20
            "\\{$rootNamespace}\\Exceptions\\Handler"
242
        );
243
244
        return $app;
245
    }
246
247
}
248