Passed
Push — master ( ff1d2c...e349ca )
by Biao
02:58
created

LaravelS::onRequest()   A

Complexity

Conditions 4
Paths 12

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 12
nop 2
dl 0
loc 17
rs 9.8666
1
<?php
2
0 ignored issues
show
Coding Style introduced by
Missing file doc comment
Loading history...
3
namespace Hhxsv5\LaravelS;
4
5
use Hhxsv5\LaravelS\Illuminate\Laravel;
6
use Hhxsv5\LaravelS\Illuminate\LaravelTrait;
7
use Hhxsv5\LaravelS\Illuminate\LogTrait;
8
use Hhxsv5\LaravelS\Swoole\DynamicResponse;
9
use Hhxsv5\LaravelS\Swoole\Events\ServerStartInterface;
10
use Hhxsv5\LaravelS\Swoole\Events\ServerStopInterface;
11
use Hhxsv5\LaravelS\Swoole\Events\WorkerErrorInterface;
12
use Hhxsv5\LaravelS\Swoole\Events\WorkerStartInterface;
13
use Hhxsv5\LaravelS\Swoole\Events\WorkerStopInterface;
14
use Hhxsv5\LaravelS\Swoole\InotifyTrait;
15
use Hhxsv5\LaravelS\Swoole\Process\CustomProcessTrait;
16
use Hhxsv5\LaravelS\Swoole\Process\ProcessTitleTrait;
17
use Hhxsv5\LaravelS\Swoole\Request;
18
use Hhxsv5\LaravelS\Swoole\Server;
19
use Hhxsv5\LaravelS\Swoole\StaticResponse;
20
use Hhxsv5\LaravelS\Swoole\Timer\TimerTrait;
21
use Illuminate\Http\Request as IlluminateRequest;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use Swoole\Http\Request as SwooleRequest;
23
use Swoole\Http\Response as SwooleResponse;
24
use Swoole\Http\Server as HttpServer;
25
use Swoole\Server\Port;
26
use Symfony\Component\Console\Style\OutputStyle;
27
use Symfony\Component\HttpFoundation\BinaryFileResponse;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFo...tion\BinaryFileResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
29
30
/**
31
 * Swoole Request => Laravel Request
32
 * Laravel Request => Laravel handle => Laravel Response
33
 * Laravel Response => Swoole Response
34
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
35
class LaravelS extends Server
36
{
37
    /**
38
     * Fix conflicts of traits
39
     */
40
    use InotifyTrait, LaravelTrait, LogTrait, ProcessTitleTrait, TimerTrait, CustomProcessTrait;
0 ignored issues
show
introduced by
The trait Hhxsv5\LaravelS\Swoole\Timer\TimerTrait requires some properties which are not provided by Hhxsv5\LaravelS\LaravelS: $setting, $pid
Loading history...
introduced by
The trait Hhxsv5\LaravelS\Swoole\Process\CustomProcessTrait requires some properties which are not provided by Hhxsv5\LaravelS\LaravelS: $setting, $pid
Loading history...
41
42
    /**@var array */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
43
    protected $laravelConf;
44
45
    /**@var Laravel */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
46
    protected $laravel;
47
48
    public function __construct(array $svrConf, array $laravelConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
49
    {
50
        parent::__construct($svrConf);
51
        $this->laravelConf = $laravelConf;
52
53
        $timerConf = isset($this->conf['timer']) ? $this->conf['timer'] : [];
54
        $timerConf['process_prefix'] = $svrConf['process_prefix'];
55
        $this->swoole->timerProcess = $this->addTimerProcess($this->swoole, $timerConf, $this->laravelConf);
0 ignored issues
show
Bug introduced by
The property timerProcess does not seem to exist on Swoole\Http\Server.
Loading history...
Bug introduced by
The property timerProcess does not seem to exist on Swoole\WebSocket\Server.
Loading history...
56
57
        $inotifyConf = isset($this->conf['inotify_reload']) ? $this->conf['inotify_reload'] : [];
58
        if (!isset($inotifyConf['watch_path'])) {
59
            $inotifyConf['watch_path'] = $this->laravelConf['root_path'];
60
        }
61
        $inotifyConf['process_prefix'] = $svrConf['process_prefix'];
62
        $this->swoole->inotifyProcess = $this->addInotifyProcess($this->swoole, $inotifyConf, $this->laravelConf);
0 ignored issues
show
Bug introduced by
The property inotifyProcess does not seem to exist on Swoole\Http\Server.
Loading history...
Bug introduced by
The property inotifyProcess does not seem to exist on Swoole\WebSocket\Server.
Loading history...
63
64
        $processes = isset($this->conf['processes']) ? $this->conf['processes'] : [];
65
        $this->swoole->customProcesses = $this->addCustomProcesses($this->swoole, $svrConf['process_prefix'], $processes, $this->laravelConf);
0 ignored issues
show
Bug introduced by
The property customProcesses does not seem to exist on Swoole\Http\Server.
Loading history...
Bug introduced by
The property customProcesses does not seem to exist on Swoole\WebSocket\Server.
Loading history...
66
67
        // Fire ServerStart event
68
        if (isset($this->conf['event_handlers']['ServerStart'])) {
69
            Laravel::autoload($this->laravelConf['root_path']);
70
            $this->fireEvent('ServerStart', ServerStartInterface::class, [$this->swoole]);
71
        }
72
    }
73
74
    protected function startWebSocket(SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function startWebSocket()
Loading history...
75
    {
76
        // Start Laravel's lifetime, then support session ...middleware.
77
        $laravelRequest = $this->convertRequest($this->laravel, $request);
78
        $this->laravel->bindRequest($laravelRequest);
79
        $this->laravel->fireEvent('laravels.received_request', [$laravelRequest]);
80
        $this->laravel->cleanProviders();
81
        $laravelResponse = $this->laravel->handleDynamic($laravelRequest);
82
        $this->laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
83
    }
84
85
    protected function endWebSocket(SwooleRequest $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

85
    protected function endWebSocket(/** @scrutinizer ignore-unused */ SwooleRequest $request)

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

Loading history...
Coding Style introduced by
Missing doc comment for function endWebSocket()
Loading history...
86
    {
87
        // End Laravel's lifetime.
88
        $this->laravel->saveSession();
89
        $this->laravel->clean();
90
    }
91
92
    protected function triggerWebSocketEvent($event, array $params)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function triggerWebSocketEvent()
Loading history...
93
    {
94
        if ($event === 'onHandShake') {
95
            $this->startWebSocket($params[0]);
96
            $params[1]->header('Server', $this->conf['server']);
97
        }
98
99
        parent::triggerWebSocketEvent($event, $params);
100
101
        switch ($event) {
102
            case 'onHandShake':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
103
                if (isset($params[1]->header['Sec-Websocket-Accept'])) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
104
                    // Successful handshake
105
                    parent::triggerWebSocketEvent('onOpen', [$this->swoole, $params[0]]);
106
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
107
                $this->endWebSocket($params[0]);
108
                break;
109
            case 'onOpen':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
110
                $this->endWebSocket($params[1]);
111
                break;
112
        }
113
    }
114
115
    protected function triggerPortEvent(Port $port, $handlerClass, $event, array $params)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function triggerPortEvent()
Loading history...
116
    {
117
        if ($event === 'onHandShake' || $event === 'onRequest') {
118
            $this->startWebSocket($params[0]);
119
            $params[1]->header('Server', $this->conf['server']);
120
        }
121
122
        parent::triggerPortEvent($port, $handlerClass, $event, $params);
123
124
        switch ($event) {
125
            case 'onHandShake':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
126
                if (isset($params[1]->header['Sec-Websocket-Accept'])) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
127
                    // Successful handshake
128
                    parent::triggerPortEvent($port, $handlerClass, 'onOpen', [$this->swoole, $params[0]]);
129
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
130
                $this->endWebSocket($params[0]);
131
                break;
132
            case 'onOpen':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
133
                $this->endWebSocket($params[1]);
134
                break;
135
        }
136
    }
137
138
    public function onShutdown(HttpServer $server)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onShutdown()
Loading history...
139
    {
140
        parent::onShutdown($server);
141
142
        // Fire ServerStop event
143
        if (isset($this->conf['event_handlers']['ServerStop'])) {
144
            $this->laravel = $this->initLaravel($this->laravelConf, $this->swoole);
145
            $this->fireEvent('ServerStop', ServerStopInterface::class, [$server]);
146
        }
147
    }
148
149
    public function onWorkerStart(HttpServer $server, $workerId)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerStart()
Loading history...
150
    {
151
        parent::onWorkerStart($server, $workerId);
152
153
        // To implement gracefully reload
154
        // Delay to create Laravel
155
        // Delay to include Laravel's autoload.php
156
        $this->laravel = $this->initLaravel($this->laravelConf, $this->swoole);
157
158
        // Fire WorkerStart event
159
        $this->fireEvent('WorkerStart', WorkerStartInterface::class, func_get_args());
160
    }
161
162
    public function onWorkerStop(HttpServer $server, $workerId)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerStop()
Loading history...
163
    {
164
        parent::onWorkerStop($server, $workerId);
165
166
        // Fire WorkerStop event
167
        $this->fireEvent('WorkerStop', WorkerStopInterface::class, func_get_args());
168
    }
169
170
    public function onWorkerError(HttpServer $server, $workerId, $workerPId, $exitCode, $signal)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerError()
Loading history...
171
    {
172
        parent::onWorkerError($server, $workerId, $workerPId, $exitCode, $signal);
173
174
        Laravel::autoload($this->laravelConf['root_path']);
175
176
        // Fire WorkerError event
177
        $this->fireEvent('WorkerError', WorkerErrorInterface::class, func_get_args());
178
    }
179
180
    protected function convertRequest(Laravel $laravel, SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function convertRequest()
Loading history...
181
    {
182
        $rawGlobals = $laravel->getRawGlobals();
183
        return (new Request($request))->toIlluminateRequest($rawGlobals['_SERVER'], $rawGlobals['_ENV']);
184
    }
185
186
    public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onRequest()
Loading history...
187
    {
188
        try {
189
            parent::onRequest($swooleRequest, $swooleResponse);
190
            $laravelRequest = $this->convertRequest($this->laravel, $swooleRequest);
191
            $this->laravel->bindRequest($laravelRequest);
192
            $this->laravel->fireEvent('laravels.received_request', [$laravelRequest]);
193
            $handleStaticSuccess = false;
194
            if ($this->conf['handle_static']) {
195
                // For Swoole < 1.9.17
196
                $handleStaticSuccess = $this->handleStaticResource($this->laravel, $laravelRequest, $swooleResponse);
197
            }
198
            if (!$handleStaticSuccess) {
199
                $this->handleDynamicResource($this->laravel, $laravelRequest, $swooleResponse);
200
            }
201
        } catch (\Exception $e) {
202
            $this->handleException($e, $swooleResponse);
203
        }
204
    }
205
206
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
207
     * @param \Exception $e
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
208
     * @param SwooleResponse $response
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
209
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
210
    protected function handleException($e, SwooleResponse $response)
211
    {
212
        $error = sprintf(
213
            'onRequest: Uncaught exception "%s"([%d]%s) at %s:%s, %s%s',
214
            get_class($e),
215
            $e->getCode(),
216
            $e->getMessage(),
217
            $e->getFile(),
218
            $e->getLine(),
219
            PHP_EOL,
220
            $e->getTraceAsString()
221
        );
222
        $this->error($error);
223
        try {
224
            $response->status(500);
225
            $response->end('Oops! An unexpected error occurred');
226
        } catch (\Exception $e) {
227
            $this->logException($e);
228
        }
229
    }
230
231
    protected function handleStaticResource(Laravel $laravel, IlluminateRequest $laravelRequest, SwooleResponse $swooleResponse)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function handleStaticResource()
Loading history...
232
    {
233
        $laravelResponse = $laravel->handleStatic($laravelRequest);
234
        if ($laravelResponse === false) {
235
            return false;
236
        }
237
        $laravelResponse->headers->set('Server', $this->conf['server'], true);
238
        $laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
239
        $response = new StaticResponse($swooleResponse, $laravelResponse);
240
        $response->setChunkLimit($this->conf['swoole']['buffer_output_size']);
241
        $response->send($this->conf['enable_gzip']);
242
        return true;
243
    }
244
245
    protected function handleDynamicResource(Laravel $laravel, IlluminateRequest $laravelRequest, SwooleResponse $swooleResponse)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function handleDynamicResource()
Loading history...
246
    {
247
        $laravel->cleanProviders();
248
        $laravelResponse = $laravel->handleDynamic($laravelRequest);
249
        $laravelResponse->headers->set('Server', $this->conf['server'], true);
250
        $laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
251
        if ($laravelResponse instanceof BinaryFileResponse) {
252
            $response = new StaticResponse($swooleResponse, $laravelResponse);
253
        } else {
254
            $response = new DynamicResponse($swooleResponse, $laravelResponse);
255
        }
256
        $response->setChunkLimit($this->conf['swoole']['buffer_output_size']);
257
        $response->send($this->conf['enable_gzip']);
258
        $laravel->clean();
259
        return true;
260
    }
261
262
    /**@var OutputStyle */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
263
    protected static $outputStyle;
264
265
    public static function setOutputStyle(OutputStyle $outputStyle)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function setOutputStyle()
Loading history...
266
    {
267
        static::$outputStyle = $outputStyle;
268
    }
269
270
    public static function getOutputStyle()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getOutputStyle()
Loading history...
271
    {
272
        return static::$outputStyle;
273
    }
274
}
275