Passed
Pull Request — master (#11)
by Sergey
02:20
created

TcpServer::start()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 17
ccs 0
cts 10
cp 0
crap 12
rs 9.9332
1
<?php
2
3
namespace Asiries335\redisSteamPhp\Server;
4
5
use Asiries335\redisSteamPhp\Listeners\ListenerInterface;
6
use React\Socket\ConnectionInterface;
7
8
/**
9
 *
10
 */
11
class TcpServer implements ServerInterface
12
{
13
14
    private array $config;
15
16
    /**
17
     * @var \React\Socket\ServerInterface
18
     */
19
    private $tcpServer = null;
20
21
22
    /**
23
     * @var ListenerInterface[]
24
     */
25
    private array $listeners;
26
27
    /**
28
     * @param array $config
29
     * @return void
30
     */
31
    public function setConfig(array $config): void {
32
        $this->config = $config;
33
    }
34
35
    /**
36
     * @return void
37
     */
38
    public function start(): void {
39
        if ($this->tcpServer !== null) {
40
            return;
41
        }
42
43
        $ip = $this->config['ip'] ?? '0.0.0.0';
44
        $port = $this->config['port'] ?? '2341';
45
46
        $this->tcpServer = new \React\Socket\TcpServer($ip . ':' . $port);
47
48
        $this->tcpServer->on('connection', function (ConnectionInterface $connection) {
49
50
            $connection->pipe($connection);
51
52
            $connection->on('data', function ($payload) {
53
                foreach ($this->listeners as $listener) {
54
                    $listener->handle($payload);
55
                }
56
            });
57
        });
58
    }
59
60
    /**
61
     * @return void
62
     */
63
    public function down(): void {
64
        $this->tcpServer->close();
65
    }
66
67
    /**
68
     * @param array $listeners
69
     * @return void
70
     */
71
    public function setListeners(array $listeners): void {
72
        $this->listeners = $listeners;
73
    }
74
}