123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452 |
- <?php
- namespace Predis\Transaction;
- use SplQueue;
- use Predis\BasicClientInterface;
- use Predis\ClientException;
- use Predis\ClientInterface;
- use Predis\CommunicationException;
- use Predis\ExecutableContextInterface;
- use Predis\NotSupportedException;
- use Predis\ResponseErrorInterface;
- use Predis\ResponseQueued;
- use Predis\ServerException;
- use Predis\Command\CommandInterface;
- use Predis\Connection\AggregatedConnectionInterface;
- use Predis\Protocol\ProtocolException;
- class MultiExecContext implements BasicClientInterface, ExecutableContextInterface
- {
- const STATE_RESET = 0;
- const STATE_INITIALIZED = 1;
- const STATE_INSIDEBLOCK = 2;
- const STATE_DISCARDED = 4;
- const STATE_CAS = 8;
- const STATE_WATCH = 16;
- private $state;
- private $canWatch;
- protected $client;
- protected $options;
- protected $commands;
-
- public function __construct(ClientInterface $client, Array $options = null)
- {
- $this->checkCapabilities($client);
- $this->options = $options ?: array();
- $this->client = $client;
- $this->reset();
- }
-
- protected function setState($flags)
- {
- $this->state = $flags;
- }
-
- protected function getState()
- {
- return $this->state;
- }
-
- protected function flagState($flags)
- {
- $this->state |= $flags;
- }
-
- protected function unflagState($flags)
- {
- $this->state &= ~$flags;
- }
-
- protected function checkState($flags)
- {
- return ($this->state & $flags) === $flags;
- }
-
- private function checkCapabilities(ClientInterface $client)
- {
- if ($client->getConnection() instanceof AggregatedConnectionInterface) {
- throw new NotSupportedException('Cannot initialize a MULTI/EXEC context when using aggregated connections');
- }
- $profile = $client->getProfile();
- if ($profile->supportsCommands(array('MULTI', 'EXEC', 'DISCARD')) === false) {
- throw new NotSupportedException('The current profile does not support MULTI, EXEC and DISCARD');
- }
- $this->canWatch = $profile->supportsCommands(array('WATCH', 'UNWATCH'));
- }
-
- private function isWatchSupported()
- {
- if ($this->canWatch === false) {
- throw new NotSupportedException('The current profile does not support WATCH and UNWATCH');
- }
- }
-
- protected function reset()
- {
- $this->setState(self::STATE_RESET);
- $this->commands = new SplQueue();
- }
-
- protected function initialize()
- {
- if ($this->checkState(self::STATE_INITIALIZED)) {
- return;
- }
- $options = $this->options;
- if (isset($options['cas']) && $options['cas']) {
- $this->flagState(self::STATE_CAS);
- }
- if (isset($options['watch'])) {
- $this->watch($options['watch']);
- }
- $cas = $this->checkState(self::STATE_CAS);
- $discarded = $this->checkState(self::STATE_DISCARDED);
- if (!$cas || ($cas && $discarded)) {
- $this->client->multi();
- if ($discarded) {
- $this->unflagState(self::STATE_CAS);
- }
- }
- $this->unflagState(self::STATE_DISCARDED);
- $this->flagState(self::STATE_INITIALIZED);
- }
-
- public function __call($method, $arguments)
- {
- $command = $this->client->createCommand($method, $arguments);
- $response = $this->executeCommand($command);
- return $response;
- }
-
- public function executeCommand(CommandInterface $command)
- {
- $this->initialize();
- if ($this->checkState(self::STATE_CAS)) {
- return $this->client->executeCommand($command);
- }
- $response = $this->client->getConnection()->executeCommand($command);
- if ($response instanceof ResponseQueued) {
- $this->commands->enqueue($command);
- } else if ($response instanceof ResponseErrorInterface) {
- throw new AbortedMultiExecException($this, $response->getMessage());
- } else {
- $this->onProtocolError('The server did not return a +QUEUED status response.');
- }
- return $this;
- }
-
- public function watch($keys)
- {
- $this->isWatchSupported();
- if ($this->checkState(self::STATE_INITIALIZED) && !$this->checkState(self::STATE_CAS)) {
- throw new ClientException('WATCH after MULTI is not allowed');
- }
- $reply = $this->client->watch($keys);
- $this->flagState(self::STATE_WATCH);
- return $reply;
- }
-
- public function multi()
- {
- if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) {
- $this->unflagState(self::STATE_CAS);
- $this->client->multi();
- } else {
- $this->initialize();
- }
- return $this;
- }
-
- public function unwatch()
- {
- $this->isWatchSupported();
- $this->unflagState(self::STATE_WATCH);
- $this->__call('unwatch', array());
- return $this;
- }
-
- public function discard()
- {
- if ($this->checkState(self::STATE_INITIALIZED)) {
- $command = $this->checkState(self::STATE_CAS) ? 'unwatch' : 'discard';
- $this->client->$command();
- $this->reset();
- $this->flagState(self::STATE_DISCARDED);
- }
- return $this;
- }
-
- public function exec()
- {
- return $this->execute();
- }
-
- private function checkBeforeExecution($callable)
- {
- if ($this->checkState(self::STATE_INSIDEBLOCK)) {
- throw new ClientException("Cannot invoke 'execute' or 'exec' inside an active client transaction block");
- }
- if ($callable) {
- if (!is_callable($callable)) {
- throw new \InvalidArgumentException('Argument passed must be a callable object');
- }
- if (!$this->commands->isEmpty()) {
- $this->discard();
- throw new ClientException('Cannot execute a transaction block after using fluent interface');
- }
- }
- if (isset($this->options['retry']) && !isset($callable)) {
- $this->discard();
- throw new \InvalidArgumentException('Automatic retries can be used only when a transaction block is provided');
- }
- }
-
- public function execute($callable = null)
- {
- $this->checkBeforeExecution($callable);
- $reply = null;
- $values = array();
- $attempts = isset($this->options['retry']) ? (int) $this->options['retry'] : 0;
- do {
- if ($callable !== null) {
- $this->executeTransactionBlock($callable);
- }
- if ($this->commands->isEmpty()) {
- if ($this->checkState(self::STATE_WATCH)) {
- $this->discard();
- }
- return null;
- }
- $reply = $this->client->exec();
- if ($reply === null) {
- if ($attempts === 0) {
- $message = 'The current transaction has been aborted by the server';
- throw new AbortedMultiExecException($this, $message);
- }
- $this->reset();
- if (isset($this->options['on_retry']) && is_callable($this->options['on_retry'])) {
- call_user_func($this->options['on_retry'], $this, $attempts);
- }
- continue;
- }
- break;
- } while ($attempts-- > 0);
- $exec = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
- $commands = $this->commands;
- $size = count($exec);
- if ($size !== count($commands)) {
- $this->onProtocolError("EXEC returned an unexpected number of replies");
- }
- $clientOpts = $this->client->getOptions();
- $useExceptions = isset($clientOpts->exceptions) ? $clientOpts->exceptions : true;
- for ($i = 0; $i < $size; $i++) {
- $commandReply = $exec[$i];
- if ($commandReply instanceof ResponseErrorInterface && $useExceptions) {
- $message = $commandReply->getMessage();
- throw new ServerException($message);
- }
- if ($commandReply instanceof \Iterator) {
- $commandReply = iterator_to_array($commandReply);
- }
- $values[$i] = $commands->dequeue()->parseResponse($commandReply);
- }
- return $values;
- }
-
- protected function executeTransactionBlock($callable)
- {
- $blockException = null;
- $this->flagState(self::STATE_INSIDEBLOCK);
- try {
- call_user_func($callable, $this);
- } catch (CommunicationException $exception) {
- $blockException = $exception;
- } catch (ServerException $exception) {
- $blockException = $exception;
- } catch (\Exception $exception) {
- $blockException = $exception;
- $this->discard();
- }
- $this->unflagState(self::STATE_INSIDEBLOCK);
- if ($blockException !== null) {
- throw $blockException;
- }
- }
-
- private function onProtocolError($message)
- {
-
-
-
- CommunicationException::handle(new ProtocolException(
- $this->client->getConnection(), $message
- ));
- }
- }
|