1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jalle19\StatusManager; |
4
|
|
|
|
5
|
|
|
use Jalle19\StatusManager\Event\InstanceStatusUpdatesEvent; |
6
|
|
|
use Psr\Log\LoggerInterface; |
7
|
|
|
use Ratchet\ConnectionInterface; |
8
|
|
|
use Ratchet\MessageComponentInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Handles events related to the WebSocket. Events are either triggered from Ratchet (onOpen etc.) |
12
|
|
|
* or from the event dispatcher in StatusManager. |
13
|
|
|
* |
14
|
|
|
* @package Jalle19\StatusManager |
15
|
|
|
* @copyright Copyright © Sam Stenvall 2016- |
16
|
|
|
* @license https://www.gnu.org/licenses/gpl.html The GNU General Public License v2.0 |
17
|
|
|
*/ |
18
|
|
|
class WebSocketManager implements MessageComponentInterface |
19
|
|
|
{ |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var LoggerInterface the logger |
23
|
|
|
*/ |
24
|
|
|
private $_logger; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var \SplObjectStorage the connected clients |
28
|
|
|
*/ |
29
|
|
|
private $_connectedClients; |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* WebSocketEventHandler constructor. |
34
|
|
|
* |
35
|
|
|
* @param LoggerInterface $logger |
36
|
|
|
*/ |
37
|
|
|
public function __construct(LoggerInterface $logger) |
38
|
|
|
{ |
39
|
|
|
$this->_logger = $logger; |
40
|
|
|
$this->_connectedClients = new \SplObjectStorage(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param InstanceStatusUpdatesEvent $event |
46
|
|
|
*/ |
47
|
|
|
public function onInstanceStatusUpdates(InstanceStatusUpdatesEvent $event) |
48
|
|
|
{ |
49
|
|
|
$this->_logger->debug('Broadcasting statuses to all clients'); |
50
|
|
|
$messages = $event->getInstanceStatusCollection(); |
51
|
|
|
|
52
|
|
|
foreach ($this->_connectedClients as $client) |
53
|
|
|
{ |
54
|
|
|
/* @var ConnectionInterface $client */ |
55
|
|
|
$client->send(json_encode($messages)); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @inheritdoc |
62
|
|
|
*/ |
63
|
|
|
public function onOpen(ConnectionInterface $conn) |
64
|
|
|
{ |
65
|
|
|
$this->_logger->info('Got client connection'); |
66
|
|
|
$this->_connectedClients->attach($conn); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @inheritdoc |
72
|
|
|
*/ |
73
|
|
|
public function onClose(ConnectionInterface $conn) |
74
|
|
|
{ |
75
|
|
|
$this->_logger->info('Got client disconnect'); |
76
|
|
|
$this->_connectedClients->detach($conn); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @inheritdoc |
82
|
|
|
*/ |
83
|
|
|
public function onError(ConnectionInterface $conn, \Exception $e) |
84
|
|
|
{ |
85
|
|
|
// TODO: Implement onError() method. |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @inheritdoc |
91
|
|
|
*/ |
92
|
|
|
public function onMessage(ConnectionInterface $from, $msg) |
93
|
|
|
{ |
94
|
|
|
// TODO: Implement onMessage() method. |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
} |
98
|
|
|
|