Passed
Push — master ( 24dafe...4d03e1 )
by Biao
04:40
created

LaravelS::convertRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
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 Symfony\Component\Console\Style\OutputStyle;
26
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...
27
28
29
/**
30
 * Swoole Request => Laravel Request
31
 * Laravel Request => Laravel handle => Laravel Response
32
 * Laravel Response => Swoole Response
33
 */
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...
34
class LaravelS extends Server
35
{
36
    /**
37
     * Fix conflicts of traits
38
     */
39
    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...
40
41
    /**@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...
42
    protected $laravelConf;
43
44
    /**@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...
45
    protected $laravel;
46
47
    public function __construct(array $svrConf, array $laravelConf)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
48
    {
49
        parent::__construct($svrConf);
50
        $this->laravelConf = $laravelConf;
51
52
        $timerCfg = isset($this->conf['timer']) ? $this->conf['timer'] : [];
53
        $timerCfg['process_prefix'] = $svrConf['process_prefix'];
54
        $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...
55
56
        $inotifyCfg = isset($this->conf['inotify_reload']) ? $this->conf['inotify_reload'] : [];
57
        if (!isset($inotifyCfg['watch_path'])) {
58
            $inotifyCfg['watch_path'] = $this->laravelConf['root_path'];
59
        }
60
        $inotifyCfg['process_prefix'] = $svrConf['process_prefix'];
61
        $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...
62
63
        $processes = isset($this->conf['processes']) ? $this->conf['processes'] : [];
64
        $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...
65
66
        // Fire ServerStart event
67
        if (isset($this->conf['event_handlers']['ServerStart'])) {
68
            Laravel::autoload($this->laravelConf['root_path']);
69
            $this->fireEvent('ServerStart', ServerStartInterface::class, [$this->swoole]);
70
        }
71
    }
72
73
    protected function startHandleHttp(SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function startHandleHttp()
Loading history...
74
    {
75
        // Start Laravel's lifetime, then support session ...middleware.
76
        $laravelRequest = $this->convertRequest($this->laravel, $request);
77
        $this->laravel->bindRequest($laravelRequest);
78
        $this->laravel->cleanProviders();
79
        $this->laravel->handleDynamic($laravelRequest);
80
    }
81
82
    protected function endHandleHttp(SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function endHandleHttp()
Loading history...
83
    {
84
        $this->laravel->saveSession();
85
        $this->laravel->clean();
86
    }
87
88
    protected function triggerWebSocketEvent($event, array $params)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function triggerWebSocketEvent()
Loading history...
89
    {
90
        if ($event === 'onHandShake') {
91
            $this->startHandleHttp($params[0]);
92
        }
93
94
        $result = parent::triggerWebSocketEvent($event, $params);
95
96
        if ($event === 'onHandShake') {
97
            if ($result === true) {
98
                $this->triggerWebSocketEvent('onOpen', [$this->swoole, $params[0]]);
99
            } else {
100
                // Handshake failed.
101
                goto EndLaravel;
102
            }
103
        }
104
105
        if ($event === 'onOpen') {
106
            // End Laravel's lifetime.
107
            EndLaravel:
108
            $this->endHandleHttp($params[1]);
109
        }
110
        return $result;
111
    }
112
113
    public function onShutdown(HttpServer $server)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onShutdown()
Loading history...
114
    {
115
        parent::onShutdown($server);
116
117
        // Fire ServerStop event
118
        if (isset($this->conf['event_handlers']['ServerStop'])) {
119
            $this->laravel = $this->initLaravel($this->laravelConf, $this->swoole);
120
            $this->fireEvent('ServerStop', ServerStopInterface::class, [$server]);
121
        }
122
    }
123
124
    public function onWorkerStart(HttpServer $server, $workerId)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerStart()
Loading history...
125
    {
126
        parent::onWorkerStart($server, $workerId);
127
128
        // To implement gracefully reload
129
        // Delay to create Laravel
130
        // Delay to include Laravel's autoload.php
131
        $this->laravel = $this->initLaravel($this->laravelConf, $this->swoole);
132
133
        // Fire WorkerStart event
134
        $this->fireEvent('WorkerStart', WorkerStartInterface::class, func_get_args());
135
    }
136
137
    public function onWorkerStop(HttpServer $server, $workerId)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onWorkerStop()
Loading history...
138
    {
139
        parent::onWorkerStop($server, $workerId);
140
141
        // Fire WorkerStop event
142
        $this->fireEvent('WorkerStop', WorkerStopInterface::class, func_get_args());
143
    }
144
145
    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...
146
    {
147
        parent::onWorkerError($server, $workerId, $workerPId, $exitCode, $signal);
148
149
        Laravel::autoload($this->laravelConf['root_path']);
150
151
        // Fire WorkerError event
152
        $this->fireEvent('WorkerError', WorkerErrorInterface::class, func_get_args());
153
    }
154
155
    protected function convertRequest(Laravel $laravel, SwooleRequest $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function convertRequest()
Loading history...
156
    {
157
        $rawGlobals = $laravel->getRawGlobals();
158
        return (new Request($request))->toIlluminateRequest($rawGlobals['_SERVER'], $rawGlobals['_ENV']);
159
    }
160
161
    public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function onRequest()
Loading history...
162
    {
163
        try {
164
            parent::onRequest($swooleRequest, $swooleResponse);
165
            $laravelRequest = $this->convertRequest($this->laravel, $swooleRequest);
166
            $this->laravel->bindRequest($laravelRequest);
167
            $this->laravel->fireEvent('laravels.received_request', [$laravelRequest]);
168
            $success = $this->handleStaticResource($this->laravel, $laravelRequest, $swooleResponse);
169
            if ($success === false) {
170
                $this->handleDynamicResource($this->laravel, $laravelRequest, $swooleResponse);
171
            }
172
        } catch (\Exception $e) {
173
            $this->handleException($e, $swooleResponse);
174
        }
175
    }
176
177
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
178
     * @param \Exception|\Throwable $e
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
179
     * @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...
180
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
181
    protected function handleException($e, SwooleResponse $response)
182
    {
183
        $error = sprintf(
184
            'onRequest: Uncaught exception "%s"([%d]%s) at %s:%s, %s%s',
185
            get_class($e),
186
            $e->getCode(),
187
            $e->getMessage(),
188
            $e->getFile(),
189
            $e->getLine(),
190
            PHP_EOL,
191
            $e->getTraceAsString()
192
        );
193
        $this->error($error);
194
        try {
195
            $response->status(500);
196
            $response->end('Oops! An unexpected error occurred');
197
        } catch (\Exception $e) {
198
            $this->logException($e);
199
        }
200
    }
201
202
    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...
203
    {
204
        // For Swoole < 1.9.17
205
        if (!empty($this->conf['handle_static'])) {
206
            $laravelResponse = $laravel->handleStatic($laravelRequest);
207
            if ($laravelResponse !== false) {
208
                $laravelResponse->headers->set('Server', $this->conf['server'], true);
209
                $laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
210
                $response = new StaticResponse($swooleResponse, $laravelResponse);
211
                $response->setChunkLimit($this->conf['swoole']['buffer_output_size']);
212
                $response->send($this->conf['enable_gzip']);
213
                return true;
214
            }
215
        }
216
        return false;
217
    }
218
219
    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...
220
    {
221
        $laravel->cleanProviders();
222
        $laravelResponse = $laravel->handleDynamic($laravelRequest);
223
        $laravelResponse->headers->set('Server', $this->conf['server'], true);
224
        $laravel->fireEvent('laravels.generated_response', [$laravelRequest, $laravelResponse]);
225
        if ($laravelResponse instanceof BinaryFileResponse) {
226
            $response = new StaticResponse($swooleResponse, $laravelResponse);
227
        } else {
228
            $response = new DynamicResponse($swooleResponse, $laravelResponse);
229
        }
230
        $response->setChunkLimit($this->conf['swoole']['buffer_output_size']);
231
        $response->send($this->conf['enable_gzip']);
232
        $laravel->clean();
233
        return true;
234
    }
235
236
    /**@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...
237
    protected static $outputStyle;
238
239
    public static function setOutputStyle(OutputStyle $outputStyle)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function setOutputStyle()
Loading history...
240
    {
241
        static::$outputStyle = $outputStyle;
242
    }
243
244
    public static function getOutputStyle()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getOutputStyle()
Loading history...
245
    {
246
        return static::$outputStyle;
247
    }
248
}
249