1 | <?php declare(strict_types = 1); |
||
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) |
|
30 | |||
31 | 2 | public function onStart(Endpoint $endpoint) |
|
32 | { |
||
33 | 2 | $this->endpoint = $endpoint; |
|
34 | |||
35 | 2 | $this->counter->set(0); |
|
36 | |||
37 | 2 | repeat(function() { |
|
38 | 2 | $this->emit(yield $this->gitamp->listen()); |
|
39 | 2 | }, 25000); |
|
40 | } |
||
41 | |||
42 | 2 | public function onHandshake(Request $request, Response $response) |
|
53 | |||
54 | public function onOpen(int $clientId, $handshakeData) |
||
62 | |||
63 | 1 | private function emit(Results $events) |
|
64 | { |
||
65 | 1 | if (!$events->hasEvents()) { |
|
66 | 1 | return; |
|
67 | } |
||
68 | |||
69 | $this->endpoint->send(null, $events->jsonEncode()); |
||
70 | } |
||
71 | |||
72 | 1 | private function sendConnectedUsersCount(int $count) |
|
73 | { |
||
74 | 1 | $this->endpoint->send(null, \json_encode(['connectedUsers' => $count])); |
|
75 | } |
||
76 | |||
77 | public function onData(int $clientId, Websocket\Message $msg) |
||
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() |
||
93 | } |
||
94 |