diff --git a/src/SubscriptionApi.php b/src/SubscriptionApi.php new file mode 100644 index 0000000..d51f431 --- /dev/null +++ b/src/SubscriptionApi.php @@ -0,0 +1,69 @@ +client = $client; + $this->requestApi = $requestApi; + + $this->client->on('message', array($this, 'handleMessage')); + } + + public function subscribe($channel) + { + return $this->respond('subscribe', func_get_args()); + } + + public function psubscribe($pattern) + { + return $this->respond('psubscribe', func_get_args()); + } + + public function unsubscribe($channel = null) + { + + } + + public function publish($channel, $message) + { + return $this->requestApi->publish($channel, $message); + } + + private function respond($name, $args) + { + return call_user_func_array(array($this->requestApi, $name), $args); + } + + public function handleMessage(ModelInterface $message) + { + if (!($message instanceof MultiBulkReply)) { + return; + } + + $parts = $message->getValueNative(); + if (count($parts) !== 3) { + return; + } + + $name = array_shift($parts); + $this->emit($name, $parts); + } +} diff --git a/tests/SubscriptionApiTest.php b/tests/SubscriptionApiTest.php new file mode 100644 index 0000000..fdd0579 --- /dev/null +++ b/tests/SubscriptionApiTest.php @@ -0,0 +1,35 @@ +client = $this->getMockBuilder('Clue\React\Redis\Client')->disableOriginalConstructor()->setMethods(array('sendRequest', 'close'))->getMock(); + $this->subscriptionApi = new SubscriptionApi($this->client); + } + + public function testSubscribe() + { + $promise = $this->subscriptionApi->subscribe('a'); + + $this->expectPromiseResolve($promise); + $this->pretendMessage(new MultiBulkReply(array(new BulkReply('subscribe'), new BulkReply('a'), new IntegerReply(1)))); + + $this->subscriptionApi->on('message', $this->expectCallableOnce()); + $this->pretendMessage(new MultiBulkReply(array(new BulkReply('message'), new BulkReply('a'), new BulkReply('data')))); + } + + private function pretendMessage(ModelInterface $model) + { + $this->client->emit('message', array($model, $this->client)); + } +}