diff --git a/src/Ratchet/Wamp/Topic.php b/src/Ratchet/Wamp/Topic.php index f1bd68a..3fe73d1 100644 --- a/src/Ratchet/Wamp/Topic.php +++ b/src/Ratchet/Wamp/Topic.php @@ -6,6 +6,13 @@ use Ratchet\ConnectionInterface; * A topic/channel containing connections that have subscribed to it */ class Topic implements \IteratorAggregate, \Countable { + /** + * If true the TopicManager will destroy this object if it's ever empty of connections + * @deprecated in v0.4 + * @type bool + */ + public $autoDelete = false; + private $id; private $subscribers; diff --git a/src/Ratchet/Wamp/TopicManager.php b/src/Ratchet/Wamp/TopicManager.php index a69e315..318b986 100644 --- a/src/Ratchet/Wamp/TopicManager.php +++ b/src/Ratchet/Wamp/TopicManager.php @@ -54,13 +54,12 @@ class TopicManager implements WsServerInterface, WampServerInterface { public function onUnsubscribe(ConnectionInterface $conn, $topic) { $topicObj = $this->getTopic($topic); - if ($conn->WAMP->subscriptions->contains($topicObj)) { - $conn->WAMP->subscriptions->detach($topicObj); - } else { + if (!$conn->WAMP->subscriptions->contains($topicObj)) { return; } - $this->topicLookup[$topic]->remove($conn); + $this->cleanTopic($topicObj, $conn); + $this->app->onUnsubscribe($conn, $topicObj); } @@ -77,11 +76,8 @@ class TopicManager implements WsServerInterface, WampServerInterface { public function onClose(ConnectionInterface $conn) { $this->app->onClose($conn); - foreach ($this->topicLookup as $topic => $storage) { - $storage->remove($conn); - if (0 === $storage->count()) { - unset($this->topicLookup[$topic]); - } + foreach ($this->topicLookup as $topic) { + $this->cleanTopic($topic, $conn); } } @@ -114,4 +110,16 @@ class TopicManager implements WsServerInterface, WampServerInterface { return $this->topicLookup[$topic]; } + + protected function cleanTopic(Topic $topic, ConnectionInterface $conn) { + if ($conn->WAMP->subscriptions->contains($topic)) { + $conn->WAMP->subscriptions->detach($topic); + } + + $this->topicLookup[$topic->getId()]->remove($conn); + + if ($topic->autoDelete && 0 === $topic->count()) { + unset($this->topicLookup[$topic->getId()]); + } + } } diff --git a/tests/unit/Wamp/TopicManagerTest.php b/tests/unit/Wamp/TopicManagerTest.php index 7439064..79ff2ff 100644 --- a/tests/unit/Wamp/TopicManagerTest.php +++ b/tests/unit/Wamp/TopicManagerTest.php @@ -170,6 +170,7 @@ class TopicManagerTest extends \PHPUnit_Framework_TestCase { $attribute->setAccessible(true); $topic = $method->invokeArgs($this->mngr, array($name)); + $topic->autoDelete = true; $this->assertCount(1, $attribute->getValue($this->mngr));