Total Complexity | 48 |
Total Lines | 432 |
Duplicated Lines | 0 % |
Changes | 41 | ||
Bugs | 6 | Features | 3 |
Complex classes like Manager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Manager, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
31 | class Manager |
||
32 | { |
||
33 | use InteractsWithWebsocket, |
||
|
|||
34 | InteractsWithSwooleTable, |
||
35 | InteractsWithSwooleQueue, |
||
36 | WithApplication; |
||
37 | |||
38 | /** |
||
39 | * Container. |
||
40 | * |
||
41 | * @var \Illuminate\Contracts\Container\Container |
||
42 | */ |
||
43 | protected $container; |
||
44 | |||
45 | /** |
||
46 | * @var string |
||
47 | */ |
||
48 | protected $framework; |
||
49 | |||
50 | /** |
||
51 | * @var string |
||
52 | */ |
||
53 | protected $basePath; |
||
54 | |||
55 | /** |
||
56 | * Server events. |
||
57 | * |
||
58 | * @var array |
||
59 | */ |
||
60 | protected $events = [ |
||
61 | 'start', |
||
62 | 'shutDown', |
||
63 | 'workerStart', |
||
64 | 'workerStop', |
||
65 | 'packet', |
||
66 | 'bufferFull', |
||
67 | 'bufferEmpty', |
||
68 | 'task', |
||
69 | 'finish', |
||
70 | 'pipeMessage', |
||
71 | 'workerError', |
||
72 | 'managerStart', |
||
73 | 'managerStop', |
||
74 | 'request', |
||
75 | ]; |
||
76 | |||
77 | /** |
||
78 | * HTTP server manager constructor. |
||
79 | * |
||
80 | * @param \Illuminate\Contracts\Container\Container $container |
||
81 | * @param string $framework |
||
82 | * @param string $basePath |
||
83 | * |
||
84 | * @throws \Exception |
||
85 | */ |
||
86 | public function __construct(Container $container, $framework, $basePath = null) |
||
87 | { |
||
88 | $this->container = $container; |
||
89 | $this->setFramework($framework); |
||
90 | $this->setBasepath($basePath); |
||
91 | $this->initialize(); |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * Run swoole server. |
||
96 | */ |
||
97 | public function run() |
||
98 | { |
||
99 | $this->container->make(Server::class)->start(); |
||
100 | } |
||
101 | |||
102 | /** |
||
103 | * Stop swoole server. |
||
104 | */ |
||
105 | public function stop() |
||
108 | } |
||
109 | |||
110 | /** |
||
111 | * Initialize. |
||
112 | */ |
||
113 | protected function initialize() |
||
114 | { |
||
115 | $this->createTables(); |
||
116 | $this->prepareWebsocket(); |
||
117 | |||
118 | if (! $this->container->make(Server::class)->taskworker) { |
||
119 | $this->setSwooleServerListeners(); |
||
120 | } |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * Set swoole server listeners. |
||
125 | */ |
||
126 | protected function setSwooleServerListeners() |
||
127 | { |
||
128 | $server = $this->container->make(Server::class); |
||
129 | foreach ($this->events as $event) { |
||
130 | $listener = Str::camel("on_$event"); |
||
131 | $callback = method_exists($this, $listener) ? [$this, $listener] : function () use ($event) { |
||
132 | $this->container->make('events')->dispatch("swoole.$event", func_get_args()); |
||
133 | }; |
||
134 | |||
135 | $server->on($event, $callback); |
||
136 | } |
||
137 | } |
||
138 | |||
139 | /** |
||
140 | * "onStart" listener. |
||
141 | */ |
||
142 | public function onStart() |
||
143 | { |
||
144 | $this->setProcessName('master process'); |
||
145 | |||
146 | $server = $this->container->make(Server::class); |
||
147 | $this->container->make(PidManager::class)->write($server->master_pid, $server->manager_pid ?? 0); |
||
148 | |||
149 | $this->container->make('events')->dispatch('swoole.start', func_get_args()); |
||
150 | } |
||
151 | |||
152 | /** |
||
153 | * The listener of "managerStart" event. |
||
154 | * |
||
155 | * @return void |
||
156 | */ |
||
157 | public function onManagerStart() |
||
158 | { |
||
159 | $this->setProcessName('manager process'); |
||
160 | |||
161 | $this->container->make('events')->dispatch('swoole.managerStart', func_get_args()); |
||
162 | } |
||
163 | |||
164 | /** |
||
165 | * "onWorkerStart" listener. |
||
166 | * |
||
167 | * @param \Swoole\Http\Server|mixed $server |
||
168 | * |
||
169 | * @throws \Exception |
||
170 | */ |
||
171 | public function onWorkerStart($server) |
||
172 | { |
||
173 | $this->clearCache(); |
||
174 | |||
175 | $this->container->make('events')->dispatch('swoole.workerStart', func_get_args()); |
||
176 | |||
177 | $this->setProcessName($server->taskworker ? 'task process' : 'worker process'); |
||
178 | |||
179 | // clear events instance in case of repeated listeners in worker process |
||
180 | Facade::clearResolvedInstance('events'); |
||
181 | |||
182 | // prepare laravel app |
||
183 | $this->getApplication(); |
||
184 | |||
185 | // bind after setting laravel app |
||
186 | $this->bindToLaravelApp(); |
||
187 | |||
188 | // prepare websocket handler and routes |
||
189 | if ($this->isServerWebsocket) { |
||
190 | $this->prepareWebsocketHandler(); |
||
191 | $this->loadWebsocketRoutes(); |
||
192 | } |
||
193 | } |
||
194 | |||
195 | /** |
||
196 | * "onRequest" listener. |
||
197 | * |
||
198 | * @param \Swoole\Http\Request $swooleRequest |
||
199 | * @param \Swoole\Http\Response $swooleResponse |
||
200 | */ |
||
201 | public function onRequest($swooleRequest, $swooleResponse) |
||
202 | { |
||
203 | $this->app->make('events')->dispatch('swoole.request'); |
||
204 | |||
205 | $this->resetOnRequest(); |
||
206 | $sandbox = $this->app->make(Sandbox::class); |
||
207 | $handleStatic = $this->container->make('config')->get('swoole_http.server.handle_static_files', true); |
||
208 | $publicPath = $this->container->make('config')->get('swoole_http.server.public_path', base_path('public')); |
||
209 | |||
210 | try { |
||
211 | // handle static file request first |
||
212 | if ($handleStatic && Request::handleStatic($swooleRequest, $swooleResponse, $publicPath)) { |
||
213 | return; |
||
214 | } |
||
215 | // transform swoole request to illuminate request |
||
216 | $illuminateRequest = Request::make($swooleRequest)->toIlluminate(); |
||
217 | |||
218 | if (!$sandbox->isLaravel()) { // is lumen app |
||
219 | $illuminateRequest = LumenRequest::createFromBase($illuminateRequest); |
||
220 | } |
||
221 | |||
222 | // set current request to sandbox |
||
223 | $sandbox->setRequest($illuminateRequest); |
||
224 | |||
225 | // enable sandbox |
||
226 | $sandbox->enable(); |
||
227 | |||
228 | // handle request via laravel/lumen's dispatcher |
||
229 | $illuminateResponse = $sandbox->run($illuminateRequest); |
||
230 | |||
231 | // send response |
||
232 | Response::make($illuminateResponse, $swooleResponse, $swooleRequest)->send(); |
||
233 | } catch (Throwable $e) { |
||
234 | try { |
||
235 | $exceptionResponse = $this->app |
||
236 | ->make(ExceptionHandler::class) |
||
237 | ->render( |
||
238 | $illuminateRequest, |
||
239 | $this->normalizeException($e) |
||
240 | ); |
||
241 | Response::make($exceptionResponse, $swooleResponse, $swooleRequest)->send(); |
||
242 | } catch (Throwable $e) { |
||
243 | $this->logServerError($e); |
||
244 | } |
||
245 | } finally { |
||
246 | // disable and recycle sandbox resource |
||
247 | $sandbox->disable(); |
||
248 | } |
||
249 | } |
||
250 | |||
251 | /** |
||
252 | * Reset on every request. |
||
253 | */ |
||
254 | protected function resetOnRequest() |
||
259 | } |
||
260 | } |
||
261 | |||
262 | /** |
||
263 | * Set onTask listener. |
||
264 | * |
||
265 | * @param mixed $server |
||
266 | * @param string|\Swoole\Server\Task $taskId or $task |
||
267 | * @param string|null $srcWorkerId |
||
268 | * @param mixed|null $data |
||
269 | */ |
||
270 | public function onTask($server, $task, $srcWorkerId = null, $data = null) |
||
292 | } |
||
293 | } |
||
294 | |||
295 | /** |
||
296 | * Set onFinish listener. |
||
297 | * |
||
298 | * @param mixed $server |
||
299 | * @param string $taskId |
||
300 | * @param mixed $data |
||
301 | */ |
||
302 | public function onFinish($server, $taskId, $data) |
||
308 | } |
||
309 | |||
310 | /** |
||
311 | * Set onShutdown listener. |
||
312 | */ |
||
313 | public function onShutdown() |
||
314 | { |
||
315 | $this->container->make(PidManager::class)->delete(); |
||
316 | } |
||
317 | |||
318 | /** |
||
319 | * Set bindings to Laravel app. |
||
320 | */ |
||
321 | protected function bindToLaravelApp() |
||
322 | { |
||
323 | $this->bindSandbox(); |
||
324 | $this->bindSwooleTable(); |
||
325 | |||
326 | if ($this->isServerWebsocket) { |
||
327 | $this->bindRoom(); |
||
328 | $this->bindWebsocket(); |
||
329 | } |
||
330 | } |
||
331 | |||
332 | /** |
||
333 | * Bind sandbox to Laravel app container. |
||
334 | */ |
||
335 | protected function bindSandbox() |
||
336 | { |
||
337 | $this->app->singleton(Sandbox::class, function ($app) { |
||
338 | return new Sandbox($app, $this->framework); |
||
339 | }); |
||
340 | |||
341 | $this->app->alias(Sandbox::class, 'swoole.sandbox'); |
||
342 | } |
||
343 | |||
344 | /** |
||
345 | * Clear APC or OPCache. |
||
346 | */ |
||
347 | protected function clearCache() |
||
348 | { |
||
349 | if (extension_loaded('apc')) { |
||
350 | apc_clear_cache(); |
||
351 | } |
||
352 | |||
353 | if (extension_loaded('Zend OPcache')) { |
||
354 | opcache_reset(); |
||
355 | } |
||
356 | } |
||
357 | |||
358 | /** |
||
359 | * Set process name. |
||
360 | * |
||
361 | * @codeCoverageIgnore |
||
362 | * |
||
363 | * @param $process |
||
364 | */ |
||
365 | protected function setProcessName($process) |
||
366 | { |
||
367 | // MacOS doesn't support modifying process name. |
||
368 | if (OS::is(OS::MAC_OS, OS::CYGWIN) || $this->isInTesting()) { |
||
369 | return; |
||
370 | } |
||
371 | $serverName = 'swoole_http_server'; |
||
372 | $appName = $this->container->make('config')->get('app.name', 'Laravel'); |
||
373 | |||
374 | $name = sprintf('%s: %s for %s', $serverName, $process, $appName); |
||
375 | |||
376 | swoole_set_process_name($name); |
||
377 | } |
||
378 | |||
379 | /** |
||
380 | * Add process to http server |
||
381 | * |
||
382 | * @param \Swoole\Process $process |
||
383 | */ |
||
384 | public function addProcess(Process $process): void |
||
385 | { |
||
386 | $this->container->make(Server::class)->addProcess($process); |
||
387 | } |
||
388 | |||
389 | /** |
||
390 | * Indicates if it's in phpunit environment. |
||
391 | * |
||
392 | * @return bool |
||
393 | */ |
||
394 | protected function isInTesting() |
||
395 | { |
||
396 | return defined('IN_PHPUNIT') && IN_PHPUNIT; |
||
397 | } |
||
398 | |||
399 | /** |
||
400 | * Log server error. |
||
401 | * |
||
402 | * @param \Throwable|\Exception $e |
||
403 | */ |
||
404 | public function logServerError(Throwable $e) |
||
405 | { |
||
406 | if ($this->isInTesting()) { |
||
407 | return; |
||
408 | } |
||
409 | |||
410 | $exception = $this->normalizeException($e); |
||
411 | $this->container->make(ConsoleOutput::class) |
||
412 | ->writeln(sprintf("<error>%s</error>", $exception)); |
||
413 | |||
414 | $this->container->make(ExceptionHandler::class) |
||
415 | ->report($exception); |
||
416 | } |
||
417 | |||
418 | /** |
||
419 | * Normalize a throwable/exception to exception. |
||
420 | * |
||
421 | * @param \Throwable|\Exception $e |
||
422 | */ |
||
423 | protected function normalizeException(Throwable $e) |
||
424 | { |
||
425 | if (! $e instanceof Exception) { |
||
426 | if ($e instanceof \ParseError) { |
||
427 | $severity = E_PARSE; |
||
428 | } elseif ($e instanceof \TypeError) { |
||
429 | $severity = E_RECOVERABLE_ERROR; |
||
430 | } else { |
||
431 | $severity = E_ERROR; |
||
432 | } |
||
433 | |||
434 | $error = [ |
||
435 | 'type' => $severity, |
||
436 | 'message' => $e->getMessage(), |
||
437 | 'file' => $e->getFile(), |
||
438 | 'line' => $e->getLine(), |
||
439 | ]; |
||
440 | |||
441 | $e = new FatalError($e->getMessage(), $e->getCode(), $error, null, true, $e->getTrace()); |
||
442 | } |
||
443 | |||
444 | return $e; |
||
445 | } |
||
446 | |||
447 | /** |
||
448 | * Indicates if the payload is async task. |
||
449 | * |
||
450 | * @param mixed $payload |
||
451 | * |
||
452 | * @return boolean |
||
453 | */ |
||
454 | protected function isAsyncTaskPayload($payload): bool |
||
463 | } |
||
464 | } |
||
465 |