Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 9 | class WebServer extends Server |
||
| 10 | { |
||
| 11 | const DEFAULT_PORT = 80; |
||
| 12 | |||
| 13 | /** @var WebClient[] */ |
||
| 14 | protected $clientMap; |
||
| 15 | protected $readType = PHP_BINARY_READ; |
||
| 16 | |||
| 17 | public function __construct($address = null, $port = self::DEFAULT_PORT) |
||
| 18 | { |
||
| 19 | parent::__construct($address, $port); |
||
| 20 | $this->addHook(Server::HOOK_CONNECT, [$this, 'onConnect']); |
||
| 21 | $this->addHook(Server::HOOK_INPUT, [$this, 'onInput']); |
||
| 22 | $this->addHook(Server::HOOK_DISCONNECT, [$this, 'onDisconnect']); |
||
| 23 | $this->run(); |
||
| 24 | } |
||
| 25 | |||
| 26 | public function onConnect(Server $server, Socket $client, $message) |
||
| 27 | { |
||
| 28 | echo "Connection\n"; |
||
| 29 | $this->clientMap[(string) $client] = new WebClient($server, $client); |
||
| 30 | } |
||
| 31 | |||
| 32 | public function onInput(Server $server, Socket $client, $message) |
||
| 33 | { |
||
| 34 | $messages = explode("\n", $message); |
||
| 35 | foreach ($messages as $message) { |
||
| 36 | $message .= "\n"; |
||
| 37 | $this->clientMap[(string) $client]->dispatch($message); |
||
| 38 | } |
||
| 39 | } |
||
| 40 | |||
| 41 | public function onDisconnect(Server $server, Socket $client, $message) |
||
| 42 | { |
||
| 43 | echo "Disconnect\n"; |
||
| 44 | unset($this->clientMap[(string) $client]); |
||
| 45 | } |
||
| 46 | } |
||
| 47 | |||
| 115 |