LaravelS::onRequest()   A
last analyzed

Complexity

Conditions 4
Paths 11

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 2
b 0
f 0
nc 11
nop 2
dl 0
loc 16
rs 9.9
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
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFo...ciousOperationException 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...
29
30
31
/**
32
 * Swoole Request => Laravel Request
33
 * Laravel Request => Laravel handle => Laravel Response
34
 * Laravel Response => Swoole Response
35
 */
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...
36
class LaravelS extends Server
37
{
38
    /**
39
     * Fix conflicts of traits
40
     */
41
    use InotifyTrait, LaravelTrait, LogTrait, ProcessTitleTrait, TimerTrait, CustomProcessTrait;
0 ignored issues
show
introduced by
The trait Hhxsv5\LaravelS\Swoole\Process\CustomProcessTrait requires some properties which are not provided by Hhxsv5\LaravelS\LaravelS: $setting, $pid
Loading history...
introduced by
The trait Hhxsv5\LaravelS\Swoole\Timer\TimerTrait requires some properties which are not provided by Hhxsv5\LaravelS\LaravelS: $setting, $pid
Loading history...
42
43
    /**@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...
44
    protected $laravelConf;
45
46
    /**@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...
47
    protected $laravel;
48
49
    public function __construct(array $svrConf, array $laravelConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
50
    {
51
        parent::__construct($svrConf);
52
        $this->laravelConf = $laravelConf;
53
54
        $timerConf = isset($this->conf['timer']) ? $this->conf['timer'] : [];
55
        $timerConf['process_prefix'] = $svrConf['process_prefix'];
56
        $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...
57
58
        $inotifyConf = isset($this->conf['inotify_reload']) ? $this->conf['inotify_reload'] : [];
59
        if (!isset($inotifyConf['watch_path'])) {
60
            $inotifyConf['watch_path'] = $this->laravelConf['root_path'];
61
        }
62
        $inotifyConf['process_prefix'] = $svrConf['process_prefix'];
63
        $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\WebSocket\Server.
Loading history...
Bug introduced by
The property inotifyProcess does not seem to exist on Swoole\Http\Server.
Loading history...
64
65
        $processes = isset($this->conf['processes']) ? $this->conf['processes'] : [];
66
        $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...
67
68
        // Fire ServerStart event
69
        if (isset($this->conf['event_handlers']['ServerStart'])) {
70
            Laravel::autoload($this->laravelConf['root_path']);
71
            $this->fireEvent('ServerStart', ServerStartInterface::class, [$this->swoole]);
72
        }
73
    }
74
75
    protected function beforeWebSocketHandShake(SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function beforeWebSocketHandShake()
Loading history...
76
    {
77
        // Start Laravel's lifetime, then support session ...middleware.
78
        $laravelRequest = $this->convertRequest($this->laravel, $request);
79
        $this->laravel->bindRequest($laravelRequest);
80
        $this->laravel->fireEvent('laravels.received_request', [$laravelRequest]);
81
        $this->laravel->cleanProviders();
82
        $laravelResponse = $this->laravel->handleDynamic($laravelRequest);
83
        $this->laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
84
    }
85
86
    protected function afterWebSocketOpen(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

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