MultiExecContext.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. namespace Predis;
  3. class MultiExecContext {
  4. private $_initialized, $_discarded, $_insideBlock, $_checkAndSet, $_watchedKeys;
  5. private $_client, $_options, $_commands, $_supportsWatch;
  6. public function __construct(Client $client, Array $options = null) {
  7. $this->checkCapabilities($client);
  8. $this->_options = $options ?: array();
  9. $this->_client = $client;
  10. $this->reset();
  11. }
  12. private function checkCapabilities(Client $client) {
  13. if (Helpers::isCluster($client->getConnection())) {
  14. throw new ClientException(
  15. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  16. );
  17. }
  18. $profile = $client->getProfile();
  19. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  20. throw new ClientException(
  21. 'The current profile does not support MULTI, EXEC and DISCARD commands'
  22. );
  23. }
  24. $this->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  25. }
  26. private function isWatchSupported() {
  27. if ($this->_supportsWatch === false) {
  28. throw new ClientException(
  29. 'The current profile does not support WATCH and UNWATCH commands'
  30. );
  31. }
  32. }
  33. private function reset() {
  34. $this->_initialized = false;
  35. $this->_discarded = false;
  36. $this->_checkAndSet = false;
  37. $this->_insideBlock = false;
  38. $this->_watchedKeys = false;
  39. $this->_commands = array();
  40. }
  41. private function initialize() {
  42. if ($this->_initialized === true) {
  43. return;
  44. }
  45. $options = $this->_options;
  46. $this->_checkAndSet = isset($options['cas']) && $options['cas'];
  47. if (isset($options['watch'])) {
  48. $this->watch($options['watch']);
  49. }
  50. if (!$this->_checkAndSet || ($this->_discarded && $this->_checkAndSet)) {
  51. $this->_client->multi();
  52. if ($this->_discarded) {
  53. $this->_checkAndSet = false;
  54. }
  55. }
  56. $this->_initialized = true;
  57. $this->_discarded = false;
  58. }
  59. public function __call($method, $arguments) {
  60. $this->initialize();
  61. $client = $this->_client;
  62. if ($this->_checkAndSet) {
  63. return call_user_func_array(array($client, $method), $arguments);
  64. }
  65. $command = $client->createCommand($method, $arguments);
  66. $response = $client->executeCommand($command);
  67. if (!$response instanceof ResponseQueued) {
  68. $this->onProtocolError('The server did not respond with a QUEUED status reply');
  69. }
  70. $this->_commands[] = $command;
  71. return $this;
  72. }
  73. public function watch($keys) {
  74. $this->isWatchSupported();
  75. $this->_watchedKeys = true;
  76. if ($this->_initialized && !$this->_checkAndSet) {
  77. throw new ClientException('WATCH inside MULTI is not allowed');
  78. }
  79. return $this->_client->watch($keys);
  80. }
  81. public function multi() {
  82. if ($this->_initialized && $this->_checkAndSet) {
  83. $this->_checkAndSet = false;
  84. $this->_client->multi();
  85. return $this;
  86. }
  87. $this->initialize();
  88. return $this;
  89. }
  90. public function unwatch() {
  91. $this->isWatchSupported();
  92. $this->_watchedKeys = false;
  93. $this->_client->unwatch();
  94. return $this;
  95. }
  96. public function discard() {
  97. if ($this->_initialized === true) {
  98. $command = $this->_checkAndSet ? 'unwatch' : 'discard';
  99. $this->_client->$command();
  100. $this->reset();
  101. $this->_discarded = true;
  102. }
  103. return $this;
  104. }
  105. public function exec() {
  106. return $this->execute();
  107. }
  108. private function checkBeforeExecution($block) {
  109. if ($this->_insideBlock === true) {
  110. throw new ClientException(
  111. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  112. );
  113. }
  114. if ($block) {
  115. if (!is_callable($block)) {
  116. throw new \InvalidArgumentException(
  117. 'Argument passed must be a callable object'
  118. );
  119. }
  120. if (count($this->_commands) > 0) {
  121. $this->discard();
  122. throw new ClientException(
  123. 'Cannot execute a transaction block after using fluent interface'
  124. );
  125. }
  126. }
  127. if (isset($this->_options['retry']) && !isset($block)) {
  128. $this->discard();
  129. throw new \InvalidArgumentException(
  130. 'Automatic retries can be used only when a transaction block is provided'
  131. );
  132. }
  133. }
  134. public function execute($block = null) {
  135. $this->checkBeforeExecution($block);
  136. $reply = null;
  137. $returnValues = array();
  138. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  139. do {
  140. $blockException = null;
  141. if ($block !== null) {
  142. $this->_insideBlock = true;
  143. try {
  144. $block($this);
  145. }
  146. catch (CommunicationException $exception) {
  147. $blockException = $exception;
  148. }
  149. catch (ServerException $exception) {
  150. $blockException = $exception;
  151. }
  152. catch (\Exception $exception) {
  153. $blockException = $exception;
  154. $this->discard();
  155. }
  156. $this->_insideBlock = false;
  157. if ($blockException !== null) {
  158. throw $blockException;
  159. }
  160. }
  161. if (count($this->_commands) === 0) {
  162. if ($this->_watchedKeys) {
  163. $this->discard();
  164. return;
  165. }
  166. return;
  167. }
  168. $reply = $this->_client->exec();
  169. if ($reply === null) {
  170. if ($attemptsLeft === 0) {
  171. throw new AbortedMultiExec(
  172. 'The current transaction has been aborted by the server'
  173. );
  174. }
  175. $this->reset();
  176. if (isset($this->_options['on_retry']) && is_callable($this->_options['on_retry'])) {
  177. call_user_func($this->_options['on_retry'], $this, $attemptsLeft);
  178. }
  179. continue;
  180. }
  181. break;
  182. } while ($attemptsLeft-- > 0);
  183. $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  184. $sizeofReplies = count($execReply);
  185. $commands = &$this->_commands;
  186. if ($sizeofReplies !== count($commands)) {
  187. $this->onProtocolError('Unexpected number of responses for a MultiExecContext');
  188. }
  189. for ($i = 0; $i < $sizeofReplies; $i++) {
  190. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  191. ? iterator_to_array($execReply[$i])
  192. : $execReply[$i]
  193. );
  194. unset($commands[$i]);
  195. }
  196. return $returnValues;
  197. }
  198. private function onProtocolError($message) {
  199. // Since a MULTI/EXEC block cannot be initialized over a clustered
  200. // connection, we can safely assume that Predis\Client::getConnection()
  201. // will always return an instance of Predis\Network\IConnectionSingle.
  202. Helpers::onCommunicationException(new ProtocolException(
  203. $this->_client->getConnection(), $message
  204. ));
  205. }
  206. }