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