Total Complexity | 80 |
Total Lines | 383 |
Duplicated Lines | 0 % |
Changes | 13 | ||
Bugs | 5 | 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) |
||
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 | if ($event === 'onHandShake') { |
||
108 | // Set default HandShake |
||
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 | $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 | if (method_exists($handler, $method)) { |
||
162 | $this->callWithCatchException(function () use ($handler, $method, $params) { |
||
163 | call_user_func_array([$handler, $method], $params); |
||
164 | }); |
||
165 | } |
||
166 | }; |
||
167 | static $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 ($event, $eventHandler) { |
||
181 | $eventHandler('on' . $event, func_get_args()); |
||
182 | }); |
||
183 | } |
||
184 | } |
||
185 | } |
||
186 | |||
187 | protected function getWebSocketHandler() |
||
188 | { |
||
189 | static $handler = null; |
||
190 | if ($handler !== null) { |
||
191 | return $handler; |
||
192 | } |
||
193 | |||
194 | $handlerClass = $this->conf['websocket']['handler']; |
||
195 | $t = new $handlerClass(); |
||
196 | if (!($t instanceof WebSocketHandlerInterface)) { |
||
197 | throw new \InvalidArgumentException(sprintf('%s must implement the interface %s', get_class($t), WebSocketHandlerInterface::class)); |
||
198 | } |
||
199 | $handler = $t; |
||
200 | return $handler; |
||
201 | } |
||
202 | |||
203 | protected function getSocketHandler(Port $port, $handlerClass) |
||
204 | { |
||
205 | static $handlers = []; |
||
206 | $portHash = spl_object_hash($port); |
||
207 | if (isset($handlers[$portHash])) { |
||
208 | return $handlers[$portHash]; |
||
209 | } |
||
210 | $t = new $handlerClass($port); |
||
211 | if (!($t instanceof PortInterface)) { |
||
212 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class TcpSocket/UdpSocket', get_class($t))); |
||
213 | } |
||
214 | $handlers[$portHash] = $t; |
||
215 | return $handlers[$portHash]; |
||
216 | } |
||
217 | |||
218 | protected function bindSwooleTables() |
||
219 | { |
||
220 | $tables = isset($this->conf['swoole_tables']) ? (array)$this->conf['swoole_tables'] : []; |
||
221 | foreach ($tables as $name => $table) { |
||
222 | $t = new Table($table['size']); |
||
223 | foreach ($table['column'] as $column) { |
||
224 | if (isset($column['size'])) { |
||
225 | $t->column($column['name'], $column['type'], $column['size']); |
||
226 | } else { |
||
227 | $t->column($column['name'], $column['type']); |
||
228 | } |
||
229 | } |
||
230 | $t->create(); |
||
231 | $name .= 'Table'; // Avoid naming conflicts |
||
232 | $this->swoole->{$name} = $t; |
||
233 | } |
||
234 | } |
||
235 | |||
236 | public function onStart(HttpServer $server) |
||
237 | { |
||
238 | $this->setProcessTitle(sprintf('%s laravels: master process', $this->conf['process_prefix'])); |
||
239 | |||
240 | if (version_compare(swoole_version(), '1.9.5', '<')) { |
||
241 | file_put_contents($this->conf['swoole']['pid_file'], $server->master_pid); |
||
242 | } |
||
243 | } |
||
244 | |||
245 | public function onShutdown(HttpServer $server) |
||
246 | { |
||
247 | } |
||
248 | |||
249 | public function onManagerStart(HttpServer $server) |
||
250 | { |
||
251 | $this->setProcessTitle(sprintf('%s laravels: manager process', $this->conf['process_prefix'])); |
||
252 | } |
||
253 | |||
254 | public function onManagerStop(HttpServer $server) |
||
255 | { |
||
256 | } |
||
257 | |||
258 | public function onWorkerStart(HttpServer $server, $workerId) |
||
259 | { |
||
260 | if ($workerId >= $server->setting['worker_num']) { |
||
261 | $process = 'task worker'; |
||
262 | } else { |
||
263 | $process = 'worker'; |
||
264 | if (!empty($this->conf['enable_coroutine_runtime'])) { |
||
265 | \Swoole\Runtime::enableCoroutine(); |
||
266 | } |
||
267 | } |
||
268 | $this->setProcessTitle(sprintf('%s laravels: %s process %d', $this->conf['process_prefix'], $process, $workerId)); |
||
269 | |||
270 | if (function_exists('opcache_reset')) { |
||
271 | opcache_reset(); |
||
272 | } |
||
273 | if (function_exists('apc_clear_cache')) { |
||
274 | apc_clear_cache(); |
||
275 | } |
||
276 | |||
277 | clearstatcache(); |
||
278 | } |
||
279 | |||
280 | public function onWorkerStop(HttpServer $server, $workerId) |
||
281 | { |
||
282 | } |
||
283 | |||
284 | public function onWorkerError(HttpServer $server, $workerId, $workerPId, $exitCode, $signal) |
||
285 | { |
||
286 | $this->error(sprintf('worker[%d] error: exitCode=%s, signal=%s', $workerId, $exitCode, $signal)); |
||
287 | } |
||
288 | |||
289 | public function onPipeMessage(HttpServer $server, $srcWorkerId, $message) |
||
290 | { |
||
291 | if ($message instanceof BaseTask) { |
||
292 | $this->onTask($server, null, $srcWorkerId, $message); |
||
293 | } |
||
294 | } |
||
295 | |||
296 | public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) |
||
297 | { |
||
298 | } |
||
299 | |||
300 | public function onHandShake(SwooleRequest $request, SwooleResponse $response) |
||
335 | } |
||
336 | |||
337 | public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data) |
||
338 | { |
||
339 | if ($data instanceof Event) { |
||
340 | $this->handleEvent($data); |
||
341 | } elseif ($data instanceof Task) { |
||
342 | if ($this->handleTask($data) && method_exists($data, 'finish')) { |
||
343 | return $data; |
||
344 | } |
||
345 | } |
||
346 | } |
||
347 | |||
348 | public function onFinish(HttpServer $server, $taskId, $data) |
||
349 | { |
||
350 | if ($data instanceof Task) { |
||
351 | $data->finish(); |
||
352 | } |
||
353 | } |
||
354 | |||
355 | protected function handleEvent(Event $event) |
||
356 | { |
||
357 | $listenerClasses = $event->getListeners(); |
||
358 | foreach ($listenerClasses as $listenerClass) { |
||
359 | /**@var Listener $listener */ |
||
360 | $listener = new $listenerClass($event); |
||
361 | if (!($listener instanceof Listener)) { |
||
362 | throw new \InvalidArgumentException(sprintf('%s must extend the abstract class %s', $listenerClass, Listener::class)); |
||
363 | } |
||
364 | $this->callWithCatchException(function () use ($listener) { |
||
365 | $listener->handle(); |
||
366 | }, [], $event->getTries()); |
||
367 | } |
||
368 | return true; |
||
369 | } |
||
370 | |||
371 | protected function handleTask(Task $task) |
||
377 | } |
||
378 | |||
379 | protected function fireEvent($event, $interface, array $arguments) |
||
380 | { |
||
381 | if (isset($this->conf['event_handlers'][$event])) { |
||
382 | $eventHandlers = (array)$this->conf['event_handlers'][$event]; |
||
383 | foreach ($eventHandlers as $eventHandler) { |
||
384 | if (!isset(class_implements($eventHandler)[$interface])) { |
||
385 | throw new \InvalidArgumentException(sprintf( |
||
386 | '%s must implement the interface %s', |
||
387 | $eventHandler, |
||
388 | $interface |
||
389 | ) |
||
390 | ); |
||
391 | } |
||
392 | $this->callWithCatchException(function () use ($eventHandler, $arguments) { |
||
393 | call_user_func_array([(new $eventHandler), 'handle'], $arguments); |
||
394 | }); |
||
395 | } |
||
396 | } |
||
397 | } |
||
398 | |||
399 | public function run() |
||
402 | } |
||
403 | } |
||
404 |