Passed
Branch v2_rewrite (3ed97e)
by Ekin
09:32
created

Handler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php declare(strict_types = 1);
2
3
namespace ekinhbayar\GitAmp\Websocket;
4
5
use Amp\Loop;
6
use Aerys\Request;
7
use Aerys\Response;
8
use Aerys\Websocket;
9
use Aerys\Websocket\Endpoint;
10
use ekinhbayar\GitAmp\Client\GitAmp;
11
use ekinhbayar\GitAmp\Response\Results;
12
use ekinhbayar\GitAmp\Storage\Counter;
13
14
class Handler implements Websocket
15
{
16
    private $endpoint;
17
18
    private $counter;
19
20
    private $origin;
21
22
    private $gitamp;
23
24 6
    public function __construct(Counter $counter, string $origin, GitAmp $gitamp)
25
    {
26 6
        $this->origin  = $origin;
27 6
        $this->counter = $counter;
28 6
        $this->gitamp  = $gitamp;
29
    }
30
31 2
    public function onStart(Endpoint $endpoint)
32
    {
33 2
        $this->endpoint = $endpoint;
34
35 2
        $this->counter->set(0);
36
    }
37
38 2
    public function onHandshake(Request $request, Response $response)
39
    {
40 2
        if ($request->getHeader('origin') !== $this->origin) {
41 1
            $response->setStatus(403);
42 1
            $response->end('<h1>origin not allowed</h1>');
43
44 1
            return null;
45
        }
46
47 1
        return $request->getConnectionInfo()['client_addr'];
48
    }
49
50 1
    public function onOpen(int $clientId, $handshakeData)
51
    {
52 1
        $this->emit(yield $this->gitamp->listen());
53
54 1
        Loop::repeat(25000, function() {
55 1
            $this->emit(yield $this->gitamp->listen());
56 1
        });
57
58 1
        $this->counter->increment();
59
60 1
        $this->sendConnectedUsersCount($this->counter->get());
61
    }
62
63 1
    private function emit(Results $events)
64
    {
65 1
        if (!$events->hasEvents()) {
66 1
            return;
67
        }
68
69
        $this->endpoint->broadcast($events->jsonEncode());
70
    }
71
72 2
    private function sendConnectedUsersCount(int $count)
73
    {
74 2
        $this->endpoint->broadcast(\json_encode(['connectedUsers' => $count]));
75
    }
76
77
    public function onData(int $clientId, Websocket\Message $msg)
78
    {
79
        // yielding $msg buffers the complete payload into a single string.
80
    }
81
82 1
    public function onClose(int $clientId, int $code, string $reason)
83
    {
84 1
        $this->counter->decrement();
85
86 1
        $this->sendConnectedUsersCount($this->counter->get());
87
    }
88
89
    public function onStop()
90
    {
91
        // intentionally left blank
92
    }
93
}
94