Passed
Push — master ( 4d03e1...2b3360 )
by Biao
04:05
created

LaravelS::onWorkerStop()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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