Passed
Push — master ( 3ca204...4858ac )
by Biao
03:09
created

LaravelS::onWorkerStart()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 11
rs 10
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 beforeWebSocketHandShake(SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function beforeWebSocketHandShake()
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 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

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