Total Complexity | 81 |
Total Lines | 386 |
Duplicated Lines | 0 % |
Changes | 12 | ||
Bugs | 4 | 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($method, array $params) |
||
99 | { |
||
100 | $this->callWithCatchException(function () use ($method, $params) { |
||
101 | $handler = $this->getWebSocketHandler(); |
||
102 | |||
103 | if (method_exists($handler, $method)) { |
||
104 | call_user_func_array([$handler, $method], $params); |
||
105 | } elseif ($method === 'onHandShake') { |
||
106 | // Set default HandShake |
||
107 | call_user_func_array([$this, 'onHandShake'], $params); |
||
108 | } |
||
109 | }); |
||
110 | } |
||
111 | |||
112 | protected function bindWebSocketEvents() |
||
113 | { |
||
114 | if ($this->enableWebSocket) { |
||
115 | $this->swoole->on('HandShake', function () { |
||
116 | $this->triggerWebSocketEvent('onHandShake', func_get_args()); |
||
117 | }); |
||
118 | |||
119 | $this->swoole->on('Open', function () { |
||
120 | $this->triggerWebSocketEvent('onOpen', func_get_args()); |
||
121 | }); |
||
122 | |||
123 | $this->swoole->on('Message', function () { |
||
124 | $this->triggerWebSocketEvent('onMessage', func_get_args()); |
||
125 | }); |
||
126 | |||
127 | $this->swoole->on('Close', function (WebSocketServer $server, $fd, $reactorId) { |
||
128 | $clientInfo = $server->getClientInfo($fd); |
||
129 | if (isset($clientInfo['websocket_status']) && $clientInfo['websocket_status'] === \WEBSOCKET_STATUS_FRAME) { |
||
130 | $this->triggerWebSocketEvent('onClose', func_get_args()); |
||
131 | } |
||
132 | // else ignore the close event for http server |
||
133 | }); |
||
134 | } |
||
135 | } |
||
136 | |||
137 | protected function bindAttachedSockets() |
||
138 | { |
||
139 | foreach ($this->attachedSockets as $socket) { |
||
140 | if (isset($socket['enable']) && !$socket['enable']) { |
||
141 | continue; |
||
142 | } |
||
143 | |||
144 | $port = $this->swoole->addListener($socket['host'], $socket['port'], $socket['type']); |
||
145 | if (!($port instanceof Port)) { |
||
146 | $errno = method_exists($this->swoole, 'getLastError') ? $this->swoole->getLastError() : 'unknown'; |
||
147 | $errstr = sprintf('listen %s:%s failed: errno=%s', $socket['host'], $socket['port'], $errno); |
||
148 | $this->error($errstr); |
||
149 | continue; |
||
150 | } |
||
151 | |||
152 | $port->set(empty($socket['settings']) ? [] : $socket['settings']); |
||
153 | |||
154 | $handlerClass = $socket['handler']; |
||
155 | $eventHandler = function ($method, array $params) use ($port, $handlerClass) { |
||
156 | $handler = $this->getSocketHandler($port, $handlerClass); |
||
157 | if (method_exists($handler, $method)) { |
||
158 | $this->callWithCatchException(function () use ($handler, $method, $params) { |
||
159 | call_user_func_array([$handler, $method], $params); |
||
160 | }); |
||
161 | } |
||
162 | }; |
||
163 | static $events = [ |
||
164 | 'Open', |
||
165 | 'HandShake', |
||
166 | 'Request', |
||
167 | 'Message', |
||
168 | 'Connect', |
||
169 | 'Close', |
||
170 | 'Receive', |
||
171 | 'Packet', |
||
172 | 'BufferFull', |
||
173 | 'BufferEmpty', |
||
174 | ]; |
||
175 | foreach ($events as $event) { |
||
176 | $port->on($event, function () use ($event, $eventHandler) { |
||
177 | $eventHandler('on' . $event, func_get_args()); |
||
178 | }); |
||
179 | } |
||
180 | } |
||
181 | } |
||
182 | |||
183 | protected function getWebSocketHandler() |
||
184 | { |
||
185 | static $handler = null; |
||
186 | if ($handler !== null) { |
||
187 | return $handler; |
||
188 | } |
||
189 | |||
190 | $handlerClass = $this->conf['websocket']['handler']; |
||
191 | $t = new $handlerClass(); |
||
192 | if (!($t instanceof WebSocketHandlerInterface)) { |
||
193 | throw new \InvalidArgumentException(sprintf('%s must implement the interface %s', get_class($t), WebSocketHandlerInterface::class)); |
||
194 | } |
||
195 | $handler = $t; |
||
196 | return $handler; |
||
197 | } |
||
198 | |||
199 | protected function getSocketHandler(Port $port, $handlerClass) |
||
200 | { |
||
201 | static $handlers = []; |
||
202 | $portHash = spl_object_hash($port); |
||
203 | if (isset($handlers[$portHash])) { |
||
204 | return $handlers[$portHash]; |
||
205 | } |
||
206 | $t = new $handlerClass($port); |
||
207 | if (!($t instanceof PortInterface)) { |
||
208 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class TcpSocket/UdpSocket', get_class($t))); |
||
209 | } |
||
210 | $handlers[$portHash] = $t; |
||
211 | return $handlers[$portHash]; |
||
212 | } |
||
213 | |||
214 | protected function bindSwooleTables() |
||
215 | { |
||
216 | $tables = isset($this->conf['swoole_tables']) ? (array)$this->conf['swoole_tables'] : []; |
||
217 | foreach ($tables as $name => $table) { |
||
218 | $t = new Table($table['size']); |
||
219 | foreach ($table['column'] as $column) { |
||
220 | if (isset($column['size'])) { |
||
221 | $t->column($column['name'], $column['type'], $column['size']); |
||
222 | } else { |
||
223 | $t->column($column['name'], $column['type']); |
||
224 | } |
||
225 | } |
||
226 | $t->create(); |
||
227 | $name .= 'Table'; // Avoid naming conflicts |
||
228 | $this->swoole->{$name} = $t; |
||
229 | } |
||
230 | } |
||
231 | |||
232 | public function onStart(HttpServer $server) |
||
233 | { |
||
234 | $this->setProcessTitle(sprintf('%s laravels: master process', $this->conf['process_prefix'])); |
||
235 | |||
236 | if (version_compare(swoole_version(), '1.9.5', '<')) { |
||
237 | file_put_contents($this->conf['swoole']['pid_file'], $server->master_pid); |
||
238 | } |
||
239 | } |
||
240 | |||
241 | public function onShutdown(HttpServer $server) |
||
242 | { |
||
243 | } |
||
244 | |||
245 | public function onManagerStart(HttpServer $server) |
||
246 | { |
||
247 | $this->setProcessTitle(sprintf('%s laravels: manager process', $this->conf['process_prefix'])); |
||
248 | } |
||
249 | |||
250 | public function onManagerStop(HttpServer $server) |
||
251 | { |
||
252 | } |
||
253 | |||
254 | public function onWorkerStart(HttpServer $server, $workerId) |
||
255 | { |
||
256 | if ($workerId >= $server->setting['worker_num']) { |
||
257 | $process = 'task worker'; |
||
258 | } else { |
||
259 | $process = 'worker'; |
||
260 | if (!empty($this->conf['enable_coroutine_runtime'])) { |
||
261 | \Swoole\Runtime::enableCoroutine(); |
||
262 | } |
||
263 | } |
||
264 | $this->setProcessTitle(sprintf('%s laravels: %s process %d', $this->conf['process_prefix'], $process, $workerId)); |
||
265 | |||
266 | if (function_exists('opcache_reset')) { |
||
267 | opcache_reset(); |
||
268 | } |
||
269 | if (function_exists('apc_clear_cache')) { |
||
270 | apc_clear_cache(); |
||
271 | } |
||
272 | |||
273 | clearstatcache(); |
||
274 | } |
||
275 | |||
276 | public function onWorkerStop(HttpServer $server, $workerId) |
||
277 | { |
||
278 | } |
||
279 | |||
280 | public function onWorkerError(HttpServer $server, $workerId, $workerPId, $exitCode, $signal) |
||
281 | { |
||
282 | $this->error(sprintf('worker[%d] error: exitCode=%s, signal=%s', $workerId, $exitCode, $signal)); |
||
283 | } |
||
284 | |||
285 | public function onPipeMessage(HttpServer $server, $srcWorkerId, $message) |
||
286 | { |
||
287 | if ($message instanceof BaseTask) { |
||
288 | $this->onTask($server, null, $srcWorkerId, $message); |
||
289 | } |
||
290 | } |
||
291 | |||
292 | public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) |
||
294 | } |
||
295 | |||
296 | public function onHandShake(SwooleRequest $request, SwooleResponse $response) |
||
337 | } |
||
338 | } |
||
339 | |||
340 | public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data) |
||
341 | { |
||
342 | if ($data instanceof Event) { |
||
343 | $this->handleEvent($data); |
||
344 | } elseif ($data instanceof Task) { |
||
345 | if ($this->handleTask($data) && method_exists($data, 'finish')) { |
||
346 | return $data; |
||
347 | } |
||
348 | } |
||
349 | } |
||
350 | |||
351 | public function onFinish(HttpServer $server, $taskId, $data) |
||
352 | { |
||
353 | if ($data instanceof Task) { |
||
354 | $data->finish(); |
||
355 | } |
||
356 | } |
||
357 | |||
358 | protected function handleEvent(Event $event) |
||
359 | { |
||
360 | $listenerClasses = $event->getListeners(); |
||
361 | foreach ($listenerClasses as $listenerClass) { |
||
362 | /**@var Listener $listener */ |
||
363 | $listener = new $listenerClass($event); |
||
364 | if (!($listener instanceof Listener)) { |
||
365 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class %s', $listenerClass, Listener::class)); |
||
366 | } |
||
367 | $this->callWithCatchException(function () use ($listener) { |
||
368 | $listener->handle(); |
||
369 | }, [], $event->getTries()); |
||
370 | } |
||
371 | return true; |
||
372 | } |
||
373 | |||
374 | protected function handleTask(Task $task) |
||
380 | } |
||
381 | |||
382 | protected function fireEvent($event, $interface, array $arguments) |
||
383 | { |
||
384 | if (isset($this->conf['event_handlers'][$event])) { |
||
385 | $eventHandlers = (array)$this->conf['event_handlers'][$event]; |
||
386 | foreach ($eventHandlers as $eventHandler) { |
||
387 | if (!isset(class_implements($eventHandler)[$interface])) { |
||
388 | throw new \InvalidArgumentException(sprintf( |
||
389 | '%s must implement the interface %s', |
||
390 | $eventHandler, |
||
391 | $interface |
||
392 | ) |
||
393 | ); |
||
394 | } |
||
395 | $this->callWithCatchException(function () use ($eventHandler, $arguments) { |
||
396 | call_user_func_array([(new $eventHandler), 'handle'], $arguments); |
||
397 | }); |
||
398 | } |
||
399 | } |
||
400 | } |
||
401 | |||
402 | public function run() |
||
405 | } |
||
406 | } |
||
407 |