Passed
Push — master ( 9df607...1628c2 )
by Biao
04:03
created

LaravelS::bindWebSocketEvent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
eloc 14
c 3
b 0
f 0
nc 2
nop 0
dl 0
loc 21
rs 9.7998
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\WebSocket\Server as WebSocketServer;
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 bindWebSocketEvents()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function bindWebSocketEvents()
Loading history...
75
    {
76
        parent::bindWebSocketEvents();
77
78
        if ($this->enableWebSocket) {
79
            $this->swoole->on('Open', function (WebSocketServer $server, SwooleRequest $request) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
80
                // Start Laravel's lifetime, then support session ...middleware.
81
                $laravelRequest = $this->convertRequest($this->laravel, $request);
82
                $this->laravel->bindRequest($laravelRequest);
83
                $this->laravel->cleanProviders();
84
                $this->laravel->handleDynamic($laravelRequest);
85
                $this->triggerWebSocketEvent('onOpen', func_get_args());
86
                $this->laravel->saveSession();
87
                $this->laravel->clean();
88
            });
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
89
        }
90
    }
91
92
    public function onShutdown(HttpServer $server)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onShutdown()
Loading history...
93
    {
94
        parent::onShutdown($server);
95
96
        // Fire ServerStop event
97
        if (isset($this->conf['event_handlers']['ServerStop'])) {
98
            $this->laravel = $this->initLaravel($this->laravelConf, $this->swoole);
99
            $this->fireEvent('ServerStop', ServerStopInterface::class, [$server]);
100
        }
101
    }
102
103
    public function onWorkerStart(HttpServer $server, $workerId)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerStart()
Loading history...
104
    {
105
        parent::onWorkerStart($server, $workerId);
106
107
        // To implement gracefully reload
108
        // Delay to create Laravel
109
        // Delay to include Laravel's autoload.php
110
        $this->laravel = $this->initLaravel($this->laravelConf, $this->swoole);
111
112
        // Fire WorkerStart event
113
        $this->fireEvent('WorkerStart', WorkerStartInterface::class, func_get_args());
114
    }
115
116
    public function onWorkerStop(HttpServer $server, $workerId)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerStop()
Loading history...
117
    {
118
        parent::onWorkerStop($server, $workerId);
119
120
        // Fire WorkerStop event
121
        $this->fireEvent('WorkerStop', WorkerStopInterface::class, func_get_args());
122
    }
123
124
    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...
125
    {
126
        parent::onWorkerError($server, $workerId, $workerPId, $exitCode, $signal);
127
128
        Laravel::autoload($this->laravelConf['root_path']);
129
130
        // Fire WorkerError event
131
        $this->fireEvent('WorkerError', WorkerErrorInterface::class, func_get_args());
132
    }
133
134
    protected function convertRequest(Laravel $laravel, SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function convertRequest()
Loading history...
135
    {
136
        $rawGlobals = $laravel->getRawGlobals();
137
        return (new Request($request))->toIlluminateRequest($rawGlobals['_SERVER'], $rawGlobals['_ENV']);
138
    }
139
140
    public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onRequest()
Loading history...
141
    {
142
        try {
143
            parent::onRequest($swooleRequest, $swooleResponse);
144
            $laravelRequest = $this->convertRequest($this->laravel, $swooleRequest);
145
            $this->laravel->bindRequest($laravelRequest);
146
            $this->laravel->fireEvent('laravels.received_request', [$laravelRequest]);
147
            $success = $this->handleStaticResource($this->laravel, $laravelRequest, $swooleResponse);
148
            if ($success === false) {
149
                $this->handleDynamicResource($this->laravel, $laravelRequest, $swooleResponse);
150
            }
151
        } catch (\Exception $e) {
152
            $this->handleException($e, $swooleResponse);
153
        }
154
    }
155
156
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
157
     * @param \Exception|\Throwable $e
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
158
     * @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...
159
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
160
    protected function handleException($e, SwooleResponse $response)
161
    {
162
        $error = sprintf(
163
            'onRequest: Uncaught exception "%s"([%d]%s) at %s:%s, %s%s',
164
            get_class($e),
165
            $e->getCode(),
166
            $e->getMessage(),
167
            $e->getFile(),
168
            $e->getLine(),
169
            PHP_EOL,
170
            $e->getTraceAsString()
171
        );
172
        $this->error($error);
173
        try {
174
            $response->status(500);
175
            $response->end('Oops! An unexpected error occurred');
176
        } catch (\Exception $e) {
177
            $this->logException($e);
178
        }
179
    }
180
181
    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...
182
    {
183
        // For Swoole < 1.9.17
184
        if (!empty($this->conf['handle_static'])) {
185
            $laravelResponse = $laravel->handleStatic($laravelRequest);
186
            if ($laravelResponse !== false) {
187
                $laravelResponse->headers->set('Server', $this->conf['server'], true);
188
                $laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
189
                $response = new StaticResponse($swooleResponse, $laravelResponse);
190
                $response->setChunkLimit($this->conf['swoole']['buffer_output_size']);
191
                $response->send($this->conf['enable_gzip']);
192
                return true;
193
            }
194
        }
195
        return false;
196
    }
197
198
    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...
199
    {
200
        $laravel->cleanProviders();
201
        $laravelResponse = $laravel->handleDynamic($laravelRequest);
202
        $laravelResponse->headers->set('Server', $this->conf['server'], true);
203
        $laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
204
        if ($laravelResponse instanceof BinaryFileResponse) {
205
            $response = new StaticResponse($swooleResponse, $laravelResponse);
206
        } else {
207
            $response = new DynamicResponse($swooleResponse, $laravelResponse);
208
        }
209
        $response->setChunkLimit($this->conf['swoole']['buffer_output_size']);
210
        $response->send($this->conf['enable_gzip']);
211
        $laravel->clean();
212
        return true;
213
    }
214
215
    /**@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...
216
    protected static $outputStyle;
217
218
    public static function setOutputStyle(OutputStyle $outputStyle)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function setOutputStyle()
Loading history...
219
    {
220
        static::$outputStyle = $outputStyle;
221
    }
222
223
    public static function getOutputStyle()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getOutputStyle()
Loading history...
224
    {
225
        return static::$outputStyle;
226
    }
227
}
228