| Total Complexity | 93 |
| Total Lines | 434 |
| Duplicated Lines | 0 % |
| Changes | 16 | ||
| 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 | /**@var array */ |
||
| 34 | protected $attachedSockets = []; |
||
| 35 | |||
| 36 | protected function __construct(array $conf) |
||
| 71 | } |
||
| 72 | |||
| 73 | protected function bindBaseEvents() |
||
| 74 | { |
||
| 75 | $this->swoole->on('Start', [$this, 'onStart']); |
||
| 76 | $this->swoole->on('Shutdown', [$this, 'onShutdown']); |
||
| 77 | $this->swoole->on('ManagerStart', [$this, 'onManagerStart']); |
||
| 78 | $this->swoole->on('ManagerStop', [$this, 'onManagerStop']); |
||
| 79 | $this->swoole->on('WorkerStart', [$this, 'onWorkerStart']); |
||
| 80 | $this->swoole->on('WorkerStop', [$this, 'onWorkerStop']); |
||
| 81 | $this->swoole->on('WorkerError', [$this, 'onWorkerError']); |
||
| 82 | $this->swoole->on('PipeMessage', [$this, 'onPipeMessage']); |
||
| 83 | } |
||
| 84 | |||
| 85 | protected function bindHttpEvents() |
||
| 88 | } |
||
| 89 | |||
| 90 | protected function bindTaskEvents() |
||
| 95 | } |
||
| 96 | } |
||
| 97 | |||
| 98 | protected function triggerWebSocketEvent($event, array $params) |
||
| 113 | }); |
||
| 114 | } |
||
| 115 | |||
| 116 | protected function bindWebSocketEvents() |
||
| 135 | } |
||
| 136 | // else ignore the close event for http server |
||
| 137 | }); |
||
| 138 | } |
||
| 139 | } |
||
| 140 | |||
| 141 | protected function bindAttachedSockets() |
||
| 142 | { |
||
| 143 | foreach ($this->attachedSockets as $socket) { |
||
| 144 | if (isset($socket['enable']) && !$socket['enable']) { |
||
| 145 | continue; |
||
| 146 | } |
||
| 147 | |||
| 148 | $port = $this->swoole->addListener($socket['host'], $socket['port'], $socket['type']); |
||
| 149 | if (!($port instanceof Port)) { |
||
| 150 | $errno = method_exists($this->swoole, 'getLastError') ? $this->swoole->getLastError() : 'unknown'; |
||
| 151 | $errstr = sprintf('listen %s:%s failed: errno=%s', $socket['host'], $socket['port'], $errno); |
||
| 152 | $this->error($errstr); |
||
| 153 | continue; |
||
| 154 | } |
||
| 155 | |||
| 156 | $port->set(empty($socket['settings']) ? [] : $socket['settings']); |
||
| 157 | |||
| 158 | $handlerClass = $socket['handler']; |
||
| 159 | $eventHandler = function ($event, array $params) use ($port, $handlerClass) { |
||
| 160 | $handler = $this->getSocketHandler($port, $handlerClass); |
||
| 161 | return $this->callWithCatchException(function () use ($handler, $event, $params) { |
||
| 162 | if (method_exists($handler, $event)) { |
||
| 163 | if ($event === 'onHandShake' || $event === 'onRequest') { |
||
| 164 | $this->startHandleHttp($params[0]); |
||
| 165 | } |
||
| 166 | if ($event === 'onOpen' && !method_exists($handler, 'onHandShake')) { |
||
| 167 | $this->startHandleHttp($params[1]); |
||
| 168 | } |
||
| 169 | |||
| 170 | $result = call_user_func_array([$handler, $event], $params); |
||
| 171 | |||
| 172 | if ($event === 'onHandShake') { |
||
| 173 | if ($result === true) { |
||
| 174 | $result = $handler->onOpen($this->swoole, $params[0]); |
||
| 175 | } |
||
| 176 | $this->endHandleHttp($params[0]); |
||
| 177 | } |
||
| 178 | if ($event === 'onOpen') { |
||
| 179 | $this->endHandleHttp($params[1]); |
||
| 180 | } |
||
| 181 | return $result; |
||
| 182 | } |
||
| 183 | |||
| 184 | // Set default HandShake |
||
| 185 | if ($event === 'onHandShake' && method_exists($handler, 'onOpen')) { |
||
| 186 | $this->startHandleHttp($params[0]); |
||
| 187 | $params[] = function () use ($handler, $params) { |
||
| 188 | call_user_func_array([$handler, 'onOpen'], func_get_args()); |
||
| 189 | $this->endHandleHttp($params[0]); |
||
| 190 | }; |
||
| 191 | return call_user_func_array([$this, 'onHandShake'], $params); |
||
| 192 | } |
||
| 193 | |||
| 194 | return null; |
||
| 195 | }); |
||
| 196 | }; |
||
| 197 | |||
| 198 | $events = [ |
||
| 199 | 'Open', |
||
| 200 | 'HandShake', |
||
| 201 | 'Request', |
||
| 202 | 'Message', |
||
| 203 | 'Connect', |
||
| 204 | 'Close', |
||
| 205 | 'Receive', |
||
| 206 | 'Packet', |
||
| 207 | 'BufferFull', |
||
| 208 | 'BufferEmpty', |
||
| 209 | ]; |
||
| 210 | foreach ($events as $event) { |
||
| 211 | $port->on($event, function () use ($event, $eventHandler) { |
||
| 212 | return $eventHandler('on' . $event, func_get_args()); |
||
| 213 | }); |
||
| 214 | } |
||
| 215 | } |
||
| 216 | } |
||
| 217 | |||
| 218 | protected function startHandleHttp(SwooleRequest $request) |
||
| 219 | { |
||
| 220 | // Implement in subclass |
||
| 221 | } |
||
| 222 | |||
| 223 | protected function endHandleHttp(SwooleRequest $request) |
||
| 224 | { |
||
| 225 | // Implement in subclass |
||
| 226 | } |
||
| 227 | |||
| 228 | protected function getWebSocketHandler() |
||
| 229 | { |
||
| 230 | static $handler = null; |
||
| 231 | if ($handler !== null) { |
||
| 232 | return $handler; |
||
| 233 | } |
||
| 234 | |||
| 235 | $handlerClass = $this->conf['websocket']['handler']; |
||
| 236 | $t = new $handlerClass(); |
||
| 237 | if (!($t instanceof WebSocketHandlerInterface)) { |
||
| 238 | throw new \InvalidArgumentException(sprintf('%s must implement the interface %s', get_class($t), WebSocketHandlerInterface::class)); |
||
| 239 | } |
||
| 240 | $handler = $t; |
||
| 241 | return $handler; |
||
| 242 | } |
||
| 243 | |||
| 244 | protected function getSocketHandler(Port $port, $handlerClass) |
||
| 245 | { |
||
| 246 | static $handlers = []; |
||
| 247 | $portHash = spl_object_hash($port); |
||
| 248 | if (isset($handlers[$portHash])) { |
||
| 249 | return $handlers[$portHash]; |
||
| 250 | } |
||
| 251 | $t = new $handlerClass($port); |
||
| 252 | if (!($t instanceof PortInterface)) { |
||
| 253 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class TcpSocket/UdpSocket', get_class($t))); |
||
| 254 | } |
||
| 255 | $handlers[$portHash] = $t; |
||
| 256 | return $handlers[$portHash]; |
||
| 257 | } |
||
| 258 | |||
| 259 | protected function bindSwooleTables() |
||
| 260 | { |
||
| 261 | $tables = isset($this->conf['swoole_tables']) ? (array)$this->conf['swoole_tables'] : []; |
||
| 262 | foreach ($tables as $name => $table) { |
||
| 263 | $t = new Table($table['size']); |
||
| 264 | foreach ($table['column'] as $column) { |
||
| 265 | if (isset($column['size'])) { |
||
| 266 | $t->column($column['name'], $column['type'], $column['size']); |
||
| 267 | } else { |
||
| 268 | $t->column($column['name'], $column['type']); |
||
| 269 | } |
||
| 270 | } |
||
| 271 | $t->create(); |
||
| 272 | $name .= 'Table'; // Avoid naming conflicts |
||
| 273 | $this->swoole->{$name} = $t; |
||
| 274 | } |
||
| 275 | } |
||
| 276 | |||
| 277 | public function onStart(HttpServer $server) |
||
| 278 | { |
||
| 279 | $this->setProcessTitle(sprintf('%s laravels: master process', $this->conf['process_prefix'])); |
||
| 280 | |||
| 281 | if (version_compare(swoole_version(), '1.9.5', '<')) { |
||
| 282 | file_put_contents($this->conf['swoole']['pid_file'], $server->master_pid); |
||
| 283 | } |
||
| 284 | } |
||
| 285 | |||
| 286 | public function onShutdown(HttpServer $server) |
||
| 287 | { |
||
| 288 | } |
||
| 289 | |||
| 290 | public function onManagerStart(HttpServer $server) |
||
| 291 | { |
||
| 292 | $this->setProcessTitle(sprintf('%s laravels: manager process', $this->conf['process_prefix'])); |
||
| 293 | } |
||
| 294 | |||
| 295 | public function onManagerStop(HttpServer $server) |
||
| 296 | { |
||
| 297 | } |
||
| 298 | |||
| 299 | public function onWorkerStart(HttpServer $server, $workerId) |
||
| 300 | { |
||
| 301 | if ($workerId >= $server->setting['worker_num']) { |
||
| 302 | $process = 'task worker'; |
||
| 303 | } else { |
||
| 304 | $process = 'worker'; |
||
| 305 | if (!empty($this->conf['enable_coroutine_runtime'])) { |
||
| 306 | \Swoole\Runtime::enableCoroutine(); |
||
| 307 | } |
||
| 308 | } |
||
| 309 | $this->setProcessTitle(sprintf('%s laravels: %s process %d', $this->conf['process_prefix'], $process, $workerId)); |
||
| 310 | |||
| 311 | if (function_exists('opcache_reset')) { |
||
| 312 | opcache_reset(); |
||
| 313 | } |
||
| 314 | if (function_exists('apc_clear_cache')) { |
||
| 315 | apc_clear_cache(); |
||
| 316 | } |
||
| 317 | |||
| 318 | clearstatcache(); |
||
| 319 | } |
||
| 320 | |||
| 321 | public function onWorkerStop(HttpServer $server, $workerId) |
||
| 322 | { |
||
| 323 | } |
||
| 324 | |||
| 325 | public function onWorkerError(HttpServer $server, $workerId, $workerPId, $exitCode, $signal) |
||
| 326 | { |
||
| 327 | $this->error(sprintf('worker[%d] error: exitCode=%s, signal=%s', $workerId, $exitCode, $signal)); |
||
| 328 | } |
||
| 329 | |||
| 330 | public function onPipeMessage(HttpServer $server, $srcWorkerId, $message) |
||
| 331 | { |
||
| 332 | if ($message instanceof BaseTask) { |
||
| 333 | $this->onTask($server, null, $srcWorkerId, $message); |
||
| 334 | } |
||
| 335 | } |
||
| 336 | |||
| 337 | public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) |
||
| 338 | { |
||
| 339 | } |
||
| 340 | |||
| 341 | public function onHandShake(SwooleRequest $request, SwooleResponse $response, callable $onOpen = null) |
||
| 386 | } |
||
| 387 | |||
| 388 | public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data) |
||
| 389 | { |
||
| 390 | if ($data instanceof Event) { |
||
| 391 | $this->handleEvent($data); |
||
| 392 | } elseif ($data instanceof Task) { |
||
| 393 | if ($this->handleTask($data) && method_exists($data, 'finish')) { |
||
| 394 | return $data; |
||
| 395 | } |
||
| 396 | } |
||
| 397 | } |
||
| 398 | |||
| 399 | public function onFinish(HttpServer $server, $taskId, $data) |
||
| 400 | { |
||
| 401 | if ($data instanceof Task) { |
||
| 402 | $data->finish(); |
||
| 403 | } |
||
| 404 | } |
||
| 405 | |||
| 406 | protected function handleEvent(Event $event) |
||
| 407 | { |
||
| 408 | $listenerClasses = $event->getListeners(); |
||
| 409 | foreach ($listenerClasses as $listenerClass) { |
||
| 410 | /**@var Listener $listener */ |
||
| 411 | $listener = new $listenerClass($event); |
||
| 412 | if (!($listener instanceof Listener)) { |
||
| 413 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class %s', $listenerClass, Listener::class)); |
||
| 414 | } |
||
| 415 | $this->callWithCatchException(function () use ($listener) { |
||
| 416 | $listener->handle(); |
||
| 417 | }, [], $event->getTries()); |
||
| 418 | } |
||
| 419 | return true; |
||
| 420 | } |
||
| 421 | |||
| 422 | protected function handleTask(Task $task) |
||
| 428 | } |
||
| 429 | |||
| 430 | protected function fireEvent($event, $interface, array $arguments) |
||
| 431 | { |
||
| 432 | if (isset($this->conf['event_handlers'][$event])) { |
||
| 433 | $eventHandlers = (array)$this->conf['event_handlers'][$event]; |
||
| 434 | foreach ($eventHandlers as $eventHandler) { |
||
| 435 | if (!isset(class_implements($eventHandler)[$interface])) { |
||
| 436 | throw new \InvalidArgumentException(sprintf( |
||
| 437 | '%s must implement the interface %s', |
||
| 438 | $eventHandler, |
||
| 439 | $interface |
||
| 440 | ) |
||
| 441 | ); |
||
| 442 | } |
||
| 443 | $this->callWithCatchException(function () use ($eventHandler, $arguments) { |
||
| 444 | call_user_func_array([(new $eventHandler), 'handle'], $arguments); |
||
| 445 | }); |
||
| 446 | } |
||
| 447 | } |
||
| 448 | } |
||
| 449 | |||
| 450 | public function run() |
||
| 453 | } |
||
| 454 | } |
||
| 455 |