1: <?php
2: namespace Ratchet\Wamp;
3: use Ratchet\ConnectionInterface;
4:
5: /**
6: * A topic/channel containing connections that have subscribed to it
7: */
8: class Topic implements \IteratorAggregate, \Countable {
9: /**
10: * If true the TopicManager will destroy this object if it's ever empty of connections
11: * @deprecated in v0.4
12: * @type bool
13: */
14: public $autoDelete = false;
15:
16: private $id;
17:
18: private $subscribers;
19:
20: /**
21: * @param string $topicId Unique ID for this object
22: */
23: public function __construct($topicId) {
24: $this->id = $topicId;
25: $this->subscribers = new \SplObjectStorage;
26: }
27:
28: /**
29: * @return string
30: */
31: public function getId() {
32: return $this->id;
33: }
34:
35: public function __toString() {
36: return $this->getId();
37: }
38:
39: /**
40: * Send a message to all the connections in this topic
41: * @param string $msg Payload to publish
42: * @param array $exclude A list of session IDs the message should be excluded from (blacklist)
43: * @param array $eligible A list of session Ids the message should be send to (whitelist)
44: * @return Topic The same Topic object to chain
45: */
46: public function broadcast($msg, array $exclude = array(), array $eligible = array()) {
47: $useEligible = (bool)count($eligible);
48: foreach ($this->subscribers as $client) {
49: if (in_array($client->WAMP->sessionId, $exclude)) {
50: continue;
51: }
52:
53: if ($useEligible && !in_array($client->WAMP->sessionId, $eligible)) {
54: continue;
55: }
56:
57: $client->event($this->id, $msg);
58: }
59:
60: return $this;
61: }
62:
63: /**
64: * @param WampConnection $conn
65: * @return boolean
66: */
67: public function has(ConnectionInterface $conn) {
68: return $this->subscribers->contains($conn);
69: }
70:
71: /**
72: * @param WampConnection $conn
73: * @return Topic
74: */
75: public function add(ConnectionInterface $conn) {
76: $this->subscribers->attach($conn);
77:
78: return $this;
79: }
80:
81: /**
82: * @param WampConnection $conn
83: * @return Topic
84: */
85: public function remove(ConnectionInterface $conn) {
86: if ($this->subscribers->contains($conn)) {
87: $this->subscribers->detach($conn);
88: }
89:
90: return $this;
91: }
92:
93: /**
94: * {@inheritdoc}
95: */
96: public function getIterator() {
97: return $this->subscribers;
98: }
99:
100: /**
101: * {@inheritdoc}
102: */
103: public function count() {
104: return $this->subscribers->count();
105: }
106: }
107: