Total Complexity | 84 |
Total Lines | 404 |
Duplicated Lines | 0 % |
Changes | 15 | ||
Bugs | 6 | 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) |
||
37 | { |
||
38 | $this->conf = $conf; |
||
39 | $this->enableWebSocket = !empty($this->conf['websocket']['enable']); |
||
40 | $this->attachedSockets = empty($this->conf['sockets']) ? [] : $this->conf['sockets']; |
||
41 | |||
42 | $ip = isset($conf['listen_ip']) ? $conf['listen_ip'] : '127.0.0.1'; |
||
43 | $port = isset($conf['listen_port']) ? $conf['listen_port'] : 5200; |
||
44 | $socketType = isset($conf['socket_type']) ? (int)$conf['socket_type'] : SWOOLE_SOCK_TCP; |
||
45 | |||
46 | if ($socketType === SWOOLE_SOCK_UNIX_STREAM) { |
||
47 | $socketDir = dirname($ip); |
||
48 | if (!file_exists($socketDir) && !mkdir($socketDir) && !is_dir($socketDir)) { |
||
49 | throw new \RuntimeException(sprintf('Directory "%s" was not created', $socketDir)); |
||
50 | } |
||
51 | } |
||
52 | |||
53 | $settings = isset($conf['swoole']) ? $conf['swoole'] : []; |
||
54 | $settings['enable_static_handler'] = !empty($conf['handle_static']); |
||
55 | |||
56 | $serverClass = $this->enableWebSocket ? WebSocketServer::class : HttpServer::class; |
||
57 | if (isset($settings['ssl_cert_file'], $settings['ssl_key_file'])) { |
||
58 | $this->swoole = new $serverClass($ip, $port, SWOOLE_PROCESS, $socketType | SWOOLE_SSL); |
||
59 | } else { |
||
60 | $this->swoole = new $serverClass($ip, $port, SWOOLE_PROCESS, $socketType); |
||
61 | } |
||
62 | |||
63 | $this->swoole->set($settings); |
||
64 | |||
65 | $this->bindBaseEvents(); |
||
66 | $this->bindHttpEvents(); |
||
67 | $this->bindTaskEvents(); |
||
68 | $this->bindWebSocketEvents(); |
||
69 | $this->bindAttachedSockets(); |
||
70 | $this->bindSwooleTables(); |
||
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() |
||
86 | { |
||
87 | $this->swoole->on('Request', [$this, 'onRequest']); |
||
88 | } |
||
89 | |||
90 | protected function bindTaskEvents() |
||
91 | { |
||
92 | if (!empty($this->conf['swoole']['task_worker_num'])) { |
||
93 | $this->swoole->on('Task', [$this, 'onTask']); |
||
94 | $this->swoole->on('Finish', [$this, 'onFinish']); |
||
95 | } |
||
96 | } |
||
97 | |||
98 | protected function triggerWebSocketEvent($event, array $params) |
||
99 | { |
||
100 | return $this->callWithCatchException(function () use ($event, $params) { |
||
101 | $handler = $this->getWebSocketHandler(); |
||
102 | |||
103 | if (method_exists($handler, $event)) { |
||
104 | return call_user_func_array([$handler, $event], $params); |
||
105 | } |
||
106 | |||
107 | // Set default HandShake |
||
108 | if ($event === 'onHandShake') { |
||
109 | return call_user_func_array([$this, 'onHandShake'], $params); |
||
110 | } |
||
111 | |||
112 | return null; |
||
113 | }); |
||
114 | } |
||
115 | |||
116 | protected function bindWebSocketEvents() |
||
117 | { |
||
118 | if ($this->enableWebSocket) { |
||
119 | $this->swoole->on('HandShake', function () { |
||
120 | return $this->triggerWebSocketEvent('onHandShake', func_get_args()); |
||
121 | }); |
||
122 | |||
123 | $this->swoole->on('Open', function () { |
||
124 | $this->triggerWebSocketEvent('onOpen', func_get_args()); |
||
125 | }); |
||
126 | |||
127 | $this->swoole->on('Message', function () { |
||
128 | $this->triggerWebSocketEvent('onMessage', func_get_args()); |
||
129 | }); |
||
130 | |||
131 | $this->swoole->on('Close', function (WebSocketServer $server, $fd, $reactorId) { |
||
132 | $clientInfo = $server->getClientInfo($fd); |
||
133 | if (isset($clientInfo['websocket_status']) && $clientInfo['websocket_status'] === \WEBSOCKET_STATUS_FRAME) { |
||
134 | $this->triggerWebSocketEvent('onClose', func_get_args()); |
||
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 ($method, array $params) use ($port, $handlerClass) { |
||
160 | $handler = $this->getSocketHandler($port, $handlerClass); |
||
161 | return $this->callWithCatchException(function () use ($handler, $method, $params) { |
||
162 | if (method_exists($handler, $method)) { |
||
163 | return call_user_func_array([$handler, $method], $params); |
||
164 | } |
||
165 | |||
166 | // Set default HandShake |
||
167 | if ($method === 'onHandShake') { |
||
168 | if (method_exists($handler, 'onOpen')) { |
||
169 | $params[] = [$handler, 'onOpen']; |
||
170 | } |
||
171 | return call_user_func_array([$this, 'onHandShake'], $params); |
||
172 | } |
||
173 | |||
174 | return null; |
||
175 | }); |
||
176 | }; |
||
177 | |||
178 | $events = [ |
||
179 | 'Open', |
||
180 | 'HandShake', |
||
181 | 'Request', |
||
182 | 'Message', |
||
183 | 'Connect', |
||
184 | 'Close', |
||
185 | 'Receive', |
||
186 | 'Packet', |
||
187 | 'BufferFull', |
||
188 | 'BufferEmpty', |
||
189 | ]; |
||
190 | foreach ($events as $event) { |
||
191 | $port->on($event, function () use ($event, $eventHandler) { |
||
192 | return $eventHandler('on' . $event, func_get_args()); |
||
193 | }); |
||
194 | } |
||
195 | } |
||
196 | } |
||
197 | |||
198 | protected function getWebSocketHandler() |
||
199 | { |
||
200 | static $handler = null; |
||
201 | if ($handler !== null) { |
||
202 | return $handler; |
||
203 | } |
||
204 | |||
205 | $handlerClass = $this->conf['websocket']['handler']; |
||
206 | $t = new $handlerClass(); |
||
207 | if (!($t instanceof WebSocketHandlerInterface)) { |
||
208 | throw new \InvalidArgumentException(sprintf('%s must implement the interface %s', get_class($t), WebSocketHandlerInterface::class)); |
||
209 | } |
||
210 | $handler = $t; |
||
211 | return $handler; |
||
212 | } |
||
213 | |||
214 | protected function getSocketHandler(Port $port, $handlerClass) |
||
215 | { |
||
216 | static $handlers = []; |
||
217 | $portHash = spl_object_hash($port); |
||
218 | if (isset($handlers[$portHash])) { |
||
219 | return $handlers[$portHash]; |
||
220 | } |
||
221 | $t = new $handlerClass($port); |
||
222 | if (!($t instanceof PortInterface)) { |
||
223 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class TcpSocket/UdpSocket', get_class($t))); |
||
224 | } |
||
225 | $handlers[$portHash] = $t; |
||
226 | return $handlers[$portHash]; |
||
227 | } |
||
228 | |||
229 | protected function bindSwooleTables() |
||
230 | { |
||
231 | $tables = isset($this->conf['swoole_tables']) ? (array)$this->conf['swoole_tables'] : []; |
||
232 | foreach ($tables as $name => $table) { |
||
233 | $t = new Table($table['size']); |
||
234 | foreach ($table['column'] as $column) { |
||
235 | if (isset($column['size'])) { |
||
236 | $t->column($column['name'], $column['type'], $column['size']); |
||
237 | } else { |
||
238 | $t->column($column['name'], $column['type']); |
||
239 | } |
||
240 | } |
||
241 | $t->create(); |
||
242 | $name .= 'Table'; // Avoid naming conflicts |
||
243 | $this->swoole->{$name} = $t; |
||
244 | } |
||
245 | } |
||
246 | |||
247 | public function onStart(HttpServer $server) |
||
248 | { |
||
249 | $this->setProcessTitle(sprintf('%s laravels: master process', $this->conf['process_prefix'])); |
||
250 | |||
251 | if (version_compare(swoole_version(), '1.9.5', '<')) { |
||
252 | file_put_contents($this->conf['swoole']['pid_file'], $server->master_pid); |
||
253 | } |
||
254 | } |
||
255 | |||
256 | public function onShutdown(HttpServer $server) |
||
257 | { |
||
258 | } |
||
259 | |||
260 | public function onManagerStart(HttpServer $server) |
||
261 | { |
||
262 | $this->setProcessTitle(sprintf('%s laravels: manager process', $this->conf['process_prefix'])); |
||
263 | } |
||
264 | |||
265 | public function onManagerStop(HttpServer $server) |
||
267 | } |
||
268 | |||
269 | public function onWorkerStart(HttpServer $server, $workerId) |
||
270 | { |
||
271 | if ($workerId >= $server->setting['worker_num']) { |
||
272 | $process = 'task worker'; |
||
273 | } else { |
||
274 | $process = 'worker'; |
||
275 | if (!empty($this->conf['enable_coroutine_runtime'])) { |
||
276 | \Swoole\Runtime::enableCoroutine(); |
||
277 | } |
||
278 | } |
||
279 | $this->setProcessTitle(sprintf('%s laravels: %s process %d', $this->conf['process_prefix'], $process, $workerId)); |
||
280 | |||
281 | if (function_exists('opcache_reset')) { |
||
282 | opcache_reset(); |
||
283 | } |
||
284 | if (function_exists('apc_clear_cache')) { |
||
285 | apc_clear_cache(); |
||
286 | } |
||
287 | |||
288 | clearstatcache(); |
||
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 | $this->onTask($server, null, $srcWorkerId, $message); |
||
304 | } |
||
305 | } |
||
306 | |||
307 | public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) |
||
308 | { |
||
309 | } |
||
310 | |||
311 | public function onHandShake(SwooleRequest $request, SwooleResponse $response, callable $onOpen = null) |
||
356 | } |
||
357 | |||
358 | public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data) |
||
359 | { |
||
360 | if ($data instanceof Event) { |
||
361 | $this->handleEvent($data); |
||
362 | } elseif ($data instanceof Task) { |
||
363 | if ($this->handleTask($data) && method_exists($data, 'finish')) { |
||
364 | return $data; |
||
365 | } |
||
366 | } |
||
367 | } |
||
368 | |||
369 | public function onFinish(HttpServer $server, $taskId, $data) |
||
370 | { |
||
371 | if ($data instanceof Task) { |
||
372 | $data->finish(); |
||
373 | } |
||
374 | } |
||
375 | |||
376 | protected function handleEvent(Event $event) |
||
377 | { |
||
378 | $listenerClasses = $event->getListeners(); |
||
379 | foreach ($listenerClasses as $listenerClass) { |
||
380 | /**@var Listener $listener */ |
||
381 | $listener = new $listenerClass($event); |
||
382 | if (!($listener instanceof Listener)) { |
||
383 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class %s', $listenerClass, Listener::class)); |
||
384 | } |
||
385 | $this->callWithCatchException(function () use ($listener) { |
||
386 | $listener->handle(); |
||
387 | }, [], $event->getTries()); |
||
388 | } |
||
389 | return true; |
||
390 | } |
||
391 | |||
392 | protected function handleTask(Task $task) |
||
398 | } |
||
399 | |||
400 | protected function fireEvent($event, $interface, array $arguments) |
||
401 | { |
||
402 | if (isset($this->conf['event_handlers'][$event])) { |
||
403 | $eventHandlers = (array)$this->conf['event_handlers'][$event]; |
||
404 | foreach ($eventHandlers as $eventHandler) { |
||
405 | if (!isset(class_implements($eventHandler)[$interface])) { |
||
406 | throw new \InvalidArgumentException(sprintf( |
||
407 | '%s must implement the interface %s', |
||
408 | $eventHandler, |
||
409 | $interface |
||
410 | ) |
||
411 | ); |
||
412 | } |
||
413 | $this->callWithCatchException(function () use ($eventHandler, $arguments) { |
||
414 | call_user_func_array([(new $eventHandler), 'handle'], $arguments); |
||
415 | }); |
||
416 | } |
||
417 | } |
||
418 | } |
||
419 | |||
420 | public function run() |
||
423 | } |
||
424 | } |
||
425 |