PubSubContext.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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\PubSub;
  11. use Predis\Client;
  12. use Predis\Helpers;
  13. use Predis\ClientException;
  14. use Predis\NotSupportedException;
  15. /**
  16. * Client-side abstraction of a Publish / Subscribe context.
  17. *
  18. * @author Daniele Alessandri <suppakilla@gmail.com>
  19. */
  20. class PubSubContext implements \Iterator
  21. {
  22. const SUBSCRIBE = 'subscribe';
  23. const UNSUBSCRIBE = 'unsubscribe';
  24. const PSUBSCRIBE = 'psubscribe';
  25. const PUNSUBSCRIBE = 'punsubscribe';
  26. const MESSAGE = 'message';
  27. const PMESSAGE = 'pmessage';
  28. const STATUS_VALID = 1; // 0b0001
  29. const STATUS_SUBSCRIBED = 2; // 0b0010
  30. const STATUS_PSUBSCRIBED = 4; // 0b0100
  31. private $client;
  32. private $position;
  33. private $options;
  34. /**
  35. * @param Client Client instance used by the context.
  36. * @param array Options for the context initialization.
  37. */
  38. public function __construct(Client $client, Array $options = null)
  39. {
  40. $this->checkCapabilities($client);
  41. $this->options = $options ?: array();
  42. $this->client = $client;
  43. $this->statusFlags = self::STATUS_VALID;
  44. $this->genericSubscribeInit('subscribe');
  45. $this->genericSubscribeInit('psubscribe');
  46. }
  47. /**
  48. * Automatically closes the context when PHP's garbage collector kicks in.
  49. */
  50. public function __destruct()
  51. {
  52. $this->closeContext(true);
  53. }
  54. /**
  55. * Checks if the passed client instance satisfies the required conditions
  56. * needed to initialize a Publish / Subscribe context.
  57. *
  58. * @param Client Client instance used by the context.
  59. */
  60. private function checkCapabilities(Client $client)
  61. {
  62. if (Helpers::isCluster($client->getConnection())) {
  63. throw new NotSupportedException('Cannot initialize a PUB/SUB context over a cluster of connections');
  64. }
  65. $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
  66. if ($client->getProfile()->supportsCommands($commands) === false) {
  67. throw new NotSupportedException('The current profile does not support PUB/SUB related commands');
  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. * Optionally, the context can be forcefully closed by dropping the
  132. * underlying connection.
  133. *
  134. * @param Boolean $force Forcefully close the context by closing the connection.
  135. * @return Boolean Returns false if there are no pending messages.
  136. */
  137. public function closeContext($force = false)
  138. {
  139. if (!$this->valid()) {
  140. return false;
  141. }
  142. if ($force) {
  143. $this->invalidate();
  144. $this->client->disconnect();
  145. }
  146. else {
  147. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  148. $this->unsubscribe();
  149. }
  150. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  151. $this->punsubscribe();
  152. }
  153. }
  154. return !$force;
  155. }
  156. /**
  157. * Writes a Redis command on the underlying connection.
  158. *
  159. * @param string $method ID of the command.
  160. * @param array $arguments List of arguments.
  161. */
  162. private function writeCommand($method, $arguments)
  163. {
  164. $arguments = Helpers::filterArrayArguments($arguments);
  165. $command = $this->client->createCommand($method, $arguments);
  166. $this->client->getConnection()->writeCommand($command);
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function rewind()
  172. {
  173. // NOOP
  174. }
  175. /**
  176. * Returns the last message payload retrieved from the server and generated
  177. * by one of the active subscriptions.
  178. *
  179. * @return array
  180. */
  181. public function current()
  182. {
  183. return $this->getValue();
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function key()
  189. {
  190. return $this->position;
  191. }
  192. /**
  193. * {@inheritdoc}
  194. */
  195. public function next()
  196. {
  197. if ($this->valid()) {
  198. $this->position++;
  199. }
  200. return $this->position;
  201. }
  202. /**
  203. * Checks if the the context is still in a valid state to continue.
  204. *
  205. * @return Boolean
  206. */
  207. public function valid()
  208. {
  209. $isValid = $this->isFlagSet(self::STATUS_VALID);
  210. $subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED;
  211. $hasSubscriptions = ($this->statusFlags & $subscriptionFlags) > 0;
  212. return $isValid && $hasSubscriptions;
  213. }
  214. /**
  215. * Resets the state of the context.
  216. */
  217. private function invalidate()
  218. {
  219. $this->statusFlags = 0; // 0b0000;
  220. }
  221. /**
  222. * Waits for a new message from the server generated by one of the active
  223. * subscriptions and returns it when available.
  224. *
  225. * @return array
  226. */
  227. private function getValue()
  228. {
  229. $response = $this->client->getConnection()->read();
  230. switch ($response[0]) {
  231. case self::SUBSCRIBE:
  232. case self::UNSUBSCRIBE:
  233. case self::PSUBSCRIBE:
  234. case self::PUNSUBSCRIBE:
  235. if ($response[2] === 0) {
  236. $this->invalidate();
  237. }
  238. case self::MESSAGE:
  239. return (object) array(
  240. 'kind' => $response[0],
  241. 'channel' => $response[1],
  242. 'payload' => $response[2],
  243. );
  244. case self::PMESSAGE:
  245. return (object) array(
  246. 'kind' => $response[0],
  247. 'pattern' => $response[1],
  248. 'channel' => $response[2],
  249. 'payload' => $response[3],
  250. );
  251. default:
  252. $message = "Received an unknown message type {$response[0]} inside of a pubsub context";
  253. throw new ClientException($message);
  254. }
  255. }
  256. }