Passed
Push — master ( a1ce6c...f5448e )
by Biao
04:49
created

LaravelS::handleException()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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