PubSubContext.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis;
  11. /**
  12. * Client-side abstraction of a Publish / Subscribe context.
  13. *
  14. * @author Daniele Alessandri <suppakilla@gmail.com>
  15. */
  16. class PubSubContext implements \Iterator
  17. {
  18. const SUBSCRIBE = 'subscribe';
  19. const UNSUBSCRIBE = 'unsubscribe';
  20. const PSUBSCRIBE = 'psubscribe';
  21. const PUNSUBSCRIBE = 'punsubscribe';
  22. const MESSAGE = 'message';
  23. const PMESSAGE = 'pmessage';
  24. const STATUS_VALID = 0x0001;
  25. const STATUS_SUBSCRIBED = 0x0010;
  26. const STATUS_PSUBSCRIBED = 0x0100;
  27. private $client;
  28. private $position;
  29. private $options;
  30. /**
  31. * @param Client Client instance used by the context.
  32. * @param array Options for the context initialization.
  33. */
  34. public function __construct(Client $client, Array $options = null)
  35. {
  36. $this->checkCapabilities($client);
  37. $this->options = $options ?: array();
  38. $this->client = $client;
  39. $this->statusFlags = self::STATUS_VALID;
  40. $this->genericSubscribeInit('subscribe');
  41. $this->genericSubscribeInit('psubscribe');
  42. }
  43. /**
  44. * Automatically closes the context when PHP's garbage collector kicks in.
  45. */
  46. public function __destruct()
  47. {
  48. $this->closeContext();
  49. }
  50. /**
  51. * Checks if the passed client instance satisfies the required conditions
  52. * needed to initialize a Publish / Subscribe context.
  53. *
  54. * @param Client Client instance used by the context.
  55. */
  56. private function checkCapabilities(Client $client)
  57. {
  58. if (Helpers::isCluster($client->getConnection())) {
  59. throw new ClientException(
  60. 'Cannot initialize a PUB/SUB context over a cluster of connections'
  61. );
  62. }
  63. $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
  64. if ($client->getProfile()->supportsCommands($commands) === false) {
  65. throw new ClientException(
  66. 'The current profile does not support PUB/SUB related commands'
  67. );
  68. }
  69. }
  70. /**
  71. * This method shares the logic to handle both SUBSCRIBE and PSUBSCRIBE.
  72. *
  73. * @param string $subscribeAction Type of subscription.
  74. */
  75. private function genericSubscribeInit($subscribeAction)
  76. {
  77. if (isset($this->options[$subscribeAction])) {
  78. $this->$subscribeAction($this->options[$subscribeAction]);
  79. }
  80. }
  81. /**
  82. * Checks if the specified flag is valid in the state of the context.
  83. *
  84. * @param int $value Flag.
  85. * @return Boolean
  86. */
  87. private function isFlagSet($value)
  88. {
  89. return ($this->statusFlags & $value) === $value;
  90. }
  91. /**
  92. * Subscribes to the specified channels.
  93. *
  94. * @param mixed $arg,... One or more channel names.
  95. */
  96. public function subscribe(/* arguments */)
  97. {
  98. $this->writeCommand(self::SUBSCRIBE, func_get_args());
  99. $this->statusFlags |= self::STATUS_SUBSCRIBED;
  100. }
  101. /**
  102. * Unsubscribes from the specified channels.
  103. *
  104. * @param mixed $arg,... One or more channel names.
  105. */
  106. public function unsubscribe(/* arguments */)
  107. {
  108. $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
  109. }
  110. /**
  111. * Subscribes to the specified channels using a pattern.
  112. *
  113. * @param mixed $arg,... One or more channel name patterns.
  114. */
  115. public function psubscribe(/* arguments */)
  116. {
  117. $this->writeCommand(self::PSUBSCRIBE, func_get_args());
  118. $this->statusFlags |= self::STATUS_PSUBSCRIBED;
  119. }
  120. /**
  121. * Unsubscribes from the specified channels using a pattern.
  122. *
  123. * @param mixed $arg,... One or more channel name patterns.
  124. */
  125. public function punsubscribe(/* arguments */)
  126. {
  127. $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
  128. }
  129. /**
  130. * Closes the context by unsubscribing from all the subscribed channels.
  131. */
  132. public function closeContext()
  133. {
  134. if ($this->valid()) {
  135. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  136. $this->unsubscribe();
  137. }
  138. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  139. $this->punsubscribe();
  140. }
  141. }
  142. }
  143. /**
  144. * Writes a Redis command on the underlying connection.
  145. *
  146. * @param string $method ID of the command.
  147. * @param array $arguments List of arguments.
  148. */
  149. private function writeCommand($method, $arguments)
  150. {
  151. $arguments = Helpers::filterArrayArguments($arguments);
  152. $command = $this->client->createCommand($method, $arguments);
  153. $this->client->getConnection()->writeCommand($command);
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function rewind()
  159. {
  160. // NOOP
  161. }
  162. /**
  163. * Returns the last message payload retrieved from the server and generated
  164. * by one of the active subscriptions.
  165. *
  166. * @return array
  167. */
  168. public function current()
  169. {
  170. return $this->getValue();
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function key()
  176. {
  177. return $this->position;
  178. }
  179. /**
  180. * {@inheritdoc}
  181. */
  182. public function next()
  183. {
  184. if ($this->isFlagSet(self::STATUS_VALID)) {
  185. $this->position++;
  186. }
  187. return $this->position;
  188. }
  189. /**
  190. * Checks if the the context is still in a valid state to continue.
  191. *
  192. * @return Boolean
  193. */
  194. public function valid()
  195. {
  196. $isValid = $this->isFlagSet(self::STATUS_VALID);
  197. $subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED;
  198. $hasSubscriptions = ($this->statusFlags & $subscriptionFlags) > 0;
  199. return $isValid && $hasSubscriptions;
  200. }
  201. /**
  202. * Resets the state of the context.
  203. */
  204. private function invalidate()
  205. {
  206. $this->statusFlags = 0x0000;
  207. }
  208. /**
  209. * Waits for a new message from the server generated by one of the active
  210. * subscriptions and returns it when available.
  211. *
  212. * @return array
  213. */
  214. private function getValue()
  215. {
  216. $response = $this->client->getConnection()->read();
  217. switch ($response[0]) {
  218. case self::SUBSCRIBE:
  219. case self::UNSUBSCRIBE:
  220. case self::PSUBSCRIBE:
  221. case self::PUNSUBSCRIBE:
  222. if ($response[2] === 0) {
  223. $this->invalidate();
  224. }
  225. case self::MESSAGE:
  226. return (object) array(
  227. 'kind' => $response[0],
  228. 'channel' => $response[1],
  229. 'payload' => $response[2],
  230. );
  231. case self::PMESSAGE:
  232. return (object) array(
  233. 'kind' => $response[0],
  234. 'pattern' => $response[1],
  235. 'channel' => $response[2],
  236. 'payload' => $response[3],
  237. );
  238. default:
  239. throw new ClientException(
  240. "Received an unknown message type {$response[0]} inside of a pubsub context"
  241. );
  242. }
  243. }
  244. }