Server::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
4
namespace SamIT\Proxy;
5
6
7
use React\Dns\Resolver\Factory;
8
use React\Dns\Resolver\Resolver;
9
use React\EventLoop\LoopInterface;
10
use React\Socket\Connection;
11
12
/**
13
 * Class Server
14
 * A server that receives proxy connections.
15
 * If no proxy header is received within 5 seconds after connection opening than the connection is closed.
16
 * The `connection` event is only triggered after receiving the header.
17
 * @package SamIT\Proxy
18
 * @event connection When an new connection has been fully set up (ie a proxy header was received).
19
 * @emits proxytimeout When a new connection failed to send a proxy header within 5 seconds after opening the connection.
20
 */
21
class Server extends \React\Socket\Server
22
{
23
    private $loop;
24
25 4
    public function __construct(LoopInterface $loop)
26
    {
27 4
        $this->loop = $loop;
28 4
        parent::__construct($loop);
29 4
    }
30
31
    /**
32
     * Handle the connection. We only emit the connection event after the proper header was received.
33
     * @param $socket
34
     */
35 2
    public function handleConnection($socket)
36
    {
37 2
        stream_set_blocking($socket, 0);
38 2
        $client = $this->createConnection($socket);
39
40
        $timer = $this->loop->addTimer(5, function() use ($client) {
41 1
            $client->removeAllListeners('init');
42 1
            $client->end('Timeout waiting for PROXY header.');
43 1
            $this->emit('proxytimeout', [new Connection($client->stream, $this->loop)]);
44 2
        });
45
46 2
        $client->on('init', function($connection) use ($client, $timer) {
47 1
            $timer->cancel();
48 1
            $this->emit('connection', [$connection]);
49 2
        });
50 2
    }
51
52
    /**
53
     * @param $socket
54
     * @return ProxyConnection
55
     */
56 2
    public function createConnection($socket)
57
    {
58 2
        return new ProxyConnection($socket, $this->loop);
59
    }
60
}