| Total Complexity | 86 |
| Total Lines | 400 |
| Duplicated Lines | 0 % |
| Changes | 22 | ||
| Bugs | 7 | Features | 3 |
Complex classes like Server 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 Server, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 22 | class Server |
||
| 23 | { |
||
| 24 | use LogTrait; |
||
| 25 | use ProcessTitleTrait; |
||
| 26 | |||
| 27 | /** Suffix for dynamic table properties to avoid naming conflicts */ |
||
| 28 | public const TABLE_PROPERTY_SUFFIX = 'Table'; |
||
| 29 | |||
| 30 | /**@var array */ |
||
| 31 | protected $conf; |
||
| 32 | |||
| 33 | /**@var HttpServer|WebSocketServer|HttpServerProxy|WebSocketServerProxy */ |
||
| 34 | protected $swoole; |
||
| 35 | |||
| 36 | /**@var bool */ |
||
| 37 | protected $enableWebSocket = false; |
||
| 38 | |||
| 39 | protected function __construct(array $conf) |
||
| 40 | { |
||
| 41 | $this->conf = $conf; |
||
| 42 | $this->enableWebSocket = !empty($this->conf['websocket']['enable']); |
||
| 43 | |||
| 44 | $ip = isset($conf['listen_ip']) ? $conf['listen_ip'] : '127.0.0.1'; |
||
| 45 | $port = isset($conf['listen_port']) ? $conf['listen_port'] : 5200; |
||
| 46 | $socketType = isset($conf['socket_type']) ? (int)$conf['socket_type'] : SWOOLE_SOCK_TCP; |
||
| 47 | |||
| 48 | if ($socketType === SWOOLE_SOCK_UNIX_STREAM) { |
||
| 49 | $socketDir = dirname($ip); |
||
| 50 | if (!file_exists($socketDir) && !mkdir($socketDir) && !is_dir($socketDir)) { |
||
| 51 | throw new \RuntimeException(sprintf('Directory "%s" was not created', $socketDir)); |
||
| 52 | } |
||
| 53 | } |
||
| 54 | |||
| 55 | $settings = isset($conf['swoole']) ? $conf['swoole'] : []; |
||
| 56 | $settings['enable_static_handler'] = !empty($conf['handle_static']); |
||
| 57 | |||
| 58 | // Use proxy classes to support dynamic properties in PHP 8.2+ |
||
| 59 | $serverClass = $this->enableWebSocket |
||
| 60 | ? WebSocketServerProxy::class |
||
| 61 | : HttpServerProxy::class; |
||
| 62 | if (isset($settings['ssl_cert_file'], $settings['ssl_key_file'])) { |
||
| 63 | $this->swoole = new $serverClass($ip, $port, SWOOLE_PROCESS, $socketType | SWOOLE_SSL); |
||
| 64 | } else { |
||
| 65 | $this->swoole = new $serverClass($ip, $port, SWOOLE_PROCESS, $socketType); |
||
| 66 | } |
||
| 67 | |||
| 68 | // Disable Coroutine |
||
| 69 | $settings['enable_coroutine'] = false; |
||
| 70 | |||
| 71 | $this->swoole->set($settings); |
||
| 72 | |||
| 73 | $this->bindBaseEvents(); |
||
| 74 | $this->bindHttpEvents(); |
||
| 75 | $this->bindTaskEvents(); |
||
| 76 | $this->bindWebSocketEvents(); |
||
| 77 | $this->bindPortEvents(); |
||
| 78 | $this->bindSwooleTables(); |
||
| 79 | |||
| 80 | // Disable Hook |
||
| 81 | class_exists('Swoole\Coroutine') && \Swoole\Coroutine::set(['hook_flags' => false]); |
||
| 82 | } |
||
| 83 | |||
| 84 | protected function bindBaseEvents() |
||
| 85 | { |
||
| 86 | $this->swoole->on('Start', [$this, 'onStart']); |
||
| 87 | $this->swoole->on('Shutdown', [$this, 'onShutdown']); |
||
| 88 | $this->swoole->on('ManagerStart', [$this, 'onManagerStart']); |
||
| 89 | $this->swoole->on('ManagerStop', [$this, 'onManagerStop']); |
||
| 90 | $this->swoole->on('WorkerStart', [$this, 'onWorkerStart']); |
||
| 91 | $this->swoole->on('WorkerStop', [$this, 'onWorkerStop']); |
||
| 92 | $this->swoole->on('WorkerError', [$this, 'onWorkerError']); |
||
| 93 | $this->swoole->on('PipeMessage', [$this, 'onPipeMessage']); |
||
| 94 | } |
||
| 95 | |||
| 96 | protected function bindHttpEvents() |
||
| 97 | { |
||
| 98 | $this->swoole->on('Request', [$this, 'onRequest']); |
||
| 99 | } |
||
| 100 | |||
| 101 | protected function bindTaskEvents() |
||
| 102 | { |
||
| 103 | if (!empty($this->conf['swoole']['task_worker_num'])) { |
||
| 104 | $this->swoole->on('Task', [$this, 'onTask']); |
||
| 105 | $this->swoole->on('Finish', [$this, 'onFinish']); |
||
| 106 | } |
||
| 107 | } |
||
| 108 | |||
| 109 | protected function triggerWebSocketEvent($event, array $params) |
||
| 110 | { |
||
| 111 | return $this->callWithCatchException(function () use ($event, $params) { |
||
| 112 | $handler = $this->getWebSocketHandler(); |
||
| 113 | |||
| 114 | if (method_exists($handler, $event)) { |
||
| 115 | call_user_func_array([$handler, $event], $params); |
||
| 116 | } elseif ($event === 'onHandShake') { |
||
| 117 | // Set default HandShake |
||
| 118 | call_user_func_array([$this, 'onHandShake'], $params); |
||
| 119 | } |
||
| 120 | }); |
||
| 121 | } |
||
| 122 | |||
| 123 | protected function bindWebSocketEvents() |
||
| 124 | { |
||
| 125 | if ($this->enableWebSocket) { |
||
| 126 | $this->swoole->on('HandShake', function () { |
||
| 127 | return $this->triggerWebSocketEvent('onHandShake', func_get_args()); |
||
| 128 | }); |
||
| 129 | |||
| 130 | $this->swoole->on('Open', function () { |
||
| 131 | $this->triggerWebSocketEvent('onOpen', func_get_args()); |
||
| 132 | }); |
||
| 133 | |||
| 134 | $this->swoole->on('Message', function () { |
||
| 135 | $this->triggerWebSocketEvent('onMessage', func_get_args()); |
||
| 136 | }); |
||
| 137 | |||
| 138 | $this->swoole->on('Close', function (WebSocketServer $server, $fd, $reactorId) { |
||
| 139 | $clientInfo = $server->getClientInfo($fd); |
||
| 140 | if (isset($clientInfo['websocket_status']) && $clientInfo['websocket_status'] === \WEBSOCKET_STATUS_FRAME) { |
||
| 141 | $this->triggerWebSocketEvent('onClose', func_get_args()); |
||
| 142 | } |
||
| 143 | // else ignore the close event for http server |
||
| 144 | }); |
||
| 145 | } |
||
| 146 | } |
||
| 147 | |||
| 148 | protected function triggerPortEvent(Port $port, $handlerClass, $event, array $params) |
||
| 149 | { |
||
| 150 | return $this->callWithCatchException(function () use ($port, $handlerClass, $event, $params) { |
||
| 151 | $handler = $this->getSocketHandler($port, $handlerClass); |
||
| 152 | |||
| 153 | if (method_exists($handler, $event)) { |
||
| 154 | call_user_func_array([$handler, $event], $params); |
||
| 155 | } elseif ($event === 'onHandShake') { |
||
| 156 | // Set default HandShake |
||
| 157 | call_user_func_array([$this, 'onHandShake'], $params); |
||
| 158 | } |
||
| 159 | }); |
||
| 160 | } |
||
| 161 | |||
| 162 | protected function bindPortEvents() |
||
| 163 | { |
||
| 164 | $sockets = empty($this->conf['sockets']) ? [] : $this->conf['sockets']; |
||
| 165 | foreach ($sockets as $socket) { |
||
| 166 | if (isset($socket['enable']) && !$socket['enable']) { |
||
| 167 | continue; |
||
| 168 | } |
||
| 169 | |||
| 170 | $port = $this->swoole->addListener($socket['host'], $socket['port'], $socket['type']); |
||
| 171 | if (!($port instanceof Port)) { |
||
| 172 | $errno = method_exists($this->swoole, 'getLastError') ? $this->swoole->getLastError() : 'unknown'; |
||
| 173 | $errstr = sprintf('listen %s:%s failed: errno=%s', $socket['host'], $socket['port'], $errno); |
||
| 174 | $this->error($errstr); |
||
| 175 | continue; |
||
| 176 | } |
||
| 177 | |||
| 178 | $port->set(empty($socket['settings']) ? [] : $socket['settings']); |
||
| 179 | |||
| 180 | $handlerClass = $socket['handler']; |
||
| 181 | |||
| 182 | $events = [ |
||
| 183 | 'Open', |
||
| 184 | 'HandShake', |
||
| 185 | 'Request', |
||
| 186 | 'Message', |
||
| 187 | 'Connect', |
||
| 188 | 'Close', |
||
| 189 | 'Receive', |
||
| 190 | 'Packet', |
||
| 191 | 'BufferFull', |
||
| 192 | 'BufferEmpty', |
||
| 193 | ]; |
||
| 194 | foreach ($events as $event) { |
||
| 195 | $port->on($event, function () use ($port, $handlerClass, $event) { |
||
| 196 | $this->triggerPortEvent($port, $handlerClass, 'on' . $event, func_get_args()); |
||
| 197 | }); |
||
| 198 | } |
||
| 199 | } |
||
| 200 | } |
||
| 201 | |||
| 202 | protected function getWebSocketHandler() |
||
| 203 | { |
||
| 204 | static $handler = null; |
||
| 205 | if ($handler !== null) { |
||
| 206 | return $handler; |
||
| 207 | } |
||
| 208 | |||
| 209 | $handlerClass = $this->conf['websocket']['handler']; |
||
| 210 | $t = new $handlerClass(); |
||
| 211 | if (!($t instanceof WebSocketHandlerInterface)) { |
||
| 212 | throw new \InvalidArgumentException(sprintf('%s must implement the interface %s', get_class($t), WebSocketHandlerInterface::class)); |
||
| 213 | } |
||
| 214 | $handler = $t; |
||
| 215 | return $handler; |
||
| 216 | } |
||
| 217 | |||
| 218 | protected function getSocketHandler(Port $port, $handlerClass) |
||
| 219 | { |
||
| 220 | static $handlers = []; |
||
| 221 | $portHash = spl_object_hash($port); |
||
| 222 | if (isset($handlers[$portHash])) { |
||
| 223 | return $handlers[$portHash]; |
||
| 224 | } |
||
| 225 | $t = new $handlerClass($port); |
||
| 226 | if (!($t instanceof PortInterface)) { |
||
| 227 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class TcpSocket/UdpSocket', get_class($t))); |
||
| 228 | } |
||
| 229 | $handlers[$portHash] = $t; |
||
| 230 | return $handlers[$portHash]; |
||
| 231 | } |
||
| 232 | |||
| 233 | protected function bindSwooleTables() |
||
| 234 | { |
||
| 235 | $tables = isset($this->conf['swoole_tables']) ? (array)$this->conf['swoole_tables'] : []; |
||
| 236 | foreach ($tables as $name => $table) { |
||
| 237 | $t = new Table($table['size']); |
||
| 238 | foreach ($table['column'] as $column) { |
||
| 239 | if (isset($column['size'])) { |
||
| 240 | $t->column($column['name'], $column['type'], $column['size']); |
||
| 241 | } else { |
||
| 242 | $t->column($column['name'], $column['type']); |
||
| 243 | } |
||
| 244 | } |
||
| 245 | $t->create(); |
||
| 246 | $name .= self::TABLE_PROPERTY_SUFFIX; // Avoid naming conflicts |
||
| 247 | $this->swoole->{$name} = $t; |
||
| 248 | } |
||
| 249 | } |
||
| 250 | |||
| 251 | public function onStart(HttpServer $server) |
||
| 252 | { |
||
| 253 | $this->setProcessTitle(sprintf('%s laravels: master process', $this->conf['process_prefix'])); |
||
| 254 | |||
| 255 | if (version_compare(SWOOLE_VERSION, '1.9.5', '<')) { |
||
| 256 | file_put_contents($this->conf['swoole']['pid_file'], $server->master_pid); |
||
| 257 | } |
||
| 258 | } |
||
| 259 | |||
| 260 | public function onShutdown(HttpServer $server) |
||
| 261 | { |
||
| 262 | } |
||
| 263 | |||
| 264 | public function onManagerStart(HttpServer $server) |
||
| 265 | { |
||
| 266 | $this->setProcessTitle(sprintf('%s laravels: manager process', $this->conf['process_prefix'])); |
||
| 267 | } |
||
| 268 | |||
| 269 | public function onManagerStop(HttpServer $server) |
||
| 270 | { |
||
| 271 | } |
||
| 272 | |||
| 273 | public function onWorkerStart(HttpServer $server, $workerId) |
||
| 274 | { |
||
| 275 | $processName = $workerId >= $server->setting['worker_num'] ? 'task worker' : 'worker'; |
||
| 276 | $this->setProcessTitle(sprintf('%s laravels: %s process %d', $this->conf['process_prefix'], $processName, $workerId)); |
||
| 277 | |||
| 278 | if (function_exists('opcache_reset')) { |
||
| 279 | opcache_reset(); |
||
| 280 | } |
||
| 281 | if (function_exists('apc_clear_cache')) { |
||
| 282 | apc_clear_cache(); |
||
| 283 | } |
||
| 284 | |||
| 285 | clearstatcache(); |
||
| 286 | |||
| 287 | // Disable Hook |
||
| 288 | class_exists('Swoole\Runtime') && \Swoole\Runtime::enableCoroutine(false); |
||
| 289 | } |
||
| 290 | |||
| 291 | public function onWorkerStop(HttpServer $server, $workerId) |
||
| 292 | { |
||
| 293 | } |
||
| 294 | |||
| 295 | public function onWorkerError(HttpServer $server, $workerId, $workerPId, $exitCode, $signal) |
||
| 298 | } |
||
| 299 | |||
| 300 | public function onPipeMessage(HttpServer $server, $srcWorkerId, $message) |
||
| 301 | { |
||
| 302 | if ($message instanceof BaseTask) { |
||
| 303 | $server->task($message); |
||
| 304 | // $this->onTask($server, null, $srcWorkerId, $message); |
||
| 305 | } elseif ($message instanceof MetricCollectorInterface) { |
||
| 306 | $message->collect([ |
||
| 307 | 'process_id' => $server->worker_id, |
||
| 308 | 'process_type' => $server->taskworker ? 'task' : 'worker', |
||
| 309 | ]); |
||
| 310 | } |
||
| 311 | } |
||
| 312 | |||
| 313 | public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) |
||
| 314 | { |
||
| 315 | } |
||
| 316 | |||
| 317 | public function onHandShake(SwooleRequest $request, SwooleResponse $response) |
||
| 351 | } |
||
| 352 | |||
| 353 | public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data) |
||
| 354 | { |
||
| 355 | if ($data instanceof Event) { |
||
| 356 | $this->handleEvent($data); |
||
| 357 | } elseif ($data instanceof Task) { |
||
| 358 | if ($this->handleTask($data) && method_exists($data, 'finish')) { |
||
| 359 | return $data; |
||
| 360 | } |
||
| 361 | } |
||
| 362 | } |
||
| 363 | |||
| 364 | public function onFinish(HttpServer $server, $taskId, $data) |
||
| 365 | { |
||
| 366 | if ($data instanceof Task) { |
||
| 367 | $data->finish(); |
||
| 368 | } |
||
| 369 | } |
||
| 370 | |||
| 371 | protected function handleEvent(Event $event) |
||
| 372 | { |
||
| 373 | $listenerClasses = $event->getListeners(); |
||
| 374 | foreach ($listenerClasses as $listenerClass) { |
||
| 375 | /**@var Listener $listener */ |
||
| 376 | $listener = new $listenerClass(); |
||
| 377 | if (!($listener instanceof Listener)) { |
||
| 378 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class %s', $listenerClass, Listener::class)); |
||
| 379 | } |
||
| 380 | |||
| 381 | $result = $this->callWithCatchException(function () use ($listener, $event) { |
||
| 382 | return $listener->handle($event); |
||
| 383 | }, [], $event->getTries()); |
||
| 384 | |||
| 385 | if ($result === false) { // Stop propagating this event to subsequent listeners |
||
| 386 | break; |
||
| 387 | } |
||
| 388 | } |
||
| 389 | } |
||
| 390 | |||
| 391 | protected function handleTask(Task $task) |
||
| 397 | } |
||
| 398 | |||
| 399 | protected function fireEvent($event, $interface, array $arguments) |
||
| 400 | { |
||
| 401 | if (isset($this->conf['event_handlers'][$event])) { |
||
| 402 | $eventHandlers = (array)$this->conf['event_handlers'][$event]; |
||
| 403 | foreach ($eventHandlers as $eventHandler) { |
||
| 404 | if (!isset(class_implements($eventHandler)[$interface])) { |
||
| 405 | throw new \InvalidArgumentException(sprintf( |
||
| 406 | '%s must implement the interface %s', |
||
| 407 | $eventHandler, |
||
| 408 | $interface |
||
| 409 | ) |
||
| 410 | ); |
||
| 411 | } |
||
| 412 | $this->callWithCatchException(function () use ($eventHandler, $arguments) { |
||
| 413 | call_user_func_array([(new $eventHandler), 'handle'], $arguments); |
||
| 414 | }); |
||
| 415 | } |
||
| 416 | } |
||
| 417 | } |
||
| 418 | |||
| 419 | public function run() |
||
| 422 | } |
||
| 423 | } |
||
| 424 |