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