MultiExecContext.php 7.8 KB

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