diff --git a/FAQ.md b/FAQ.md index 69e089b9..7b731931 100644 --- a/FAQ.md +++ b/FAQ.md @@ -70,8 +70,7 @@ $client = new Predis\Client(); try { $client->connect(); -} -catch (Predis\Connection\ConnectionException $exception) { +} catch (Predis\Connection\ConnectionException $exception) { // We could not connect to Redis! Your handling code goes here. } diff --git a/README.md b/README.md index e2eaf631..bb3860e9 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ $redis = new Predis\Client(array( array('host' => '10.0.0.2', 'port' => 6379) )); -$replies = $redis->pipeline(function($pipe) { +$replies = $redis->pipeline(function ($pipe) { for ($i = 0; $i < 1000; $i++) { $pipe->set("key:$i", str_pad($i, 4, '0', 0)); $pipe->get("key:$i"); diff --git a/bin/create-phar.php b/bin/create-phar.php index f9cfdc5c..fe0d31b2 100755 --- a/bin/create-phar.php +++ b/bin/create-phar.php @@ -50,7 +50,7 @@ function getPharStub($options) return <<getFQN(); }, $phpNamespace->getClasses()); + $nsClassesFQNs = array_map(function ($cl) { return $cl->getFQN(); }, $phpNamespace->getClasses()); $nsOrderedClasses = array(); foreach ($nsClassesFQNs as $nsClassFQN) { @@ -352,7 +352,9 @@ class PhpUseDirectives implements Countable, IteratorAggregate public function getPhpCode() { - $reducer = function($str, $use) { return $str .= "use $use;\n"; }; + $reducer = function ($str, $use) { + return $str .= "use $use;\n"; + }; return array_reduce($this->getList(), $reducer, ''); } @@ -430,7 +432,7 @@ LICENSE; { $useDirectives = $this->getNamespace()->getUseDirectives(); - $useExtractor = function($m) use($useDirectives) { + $useExtractor = function ($m) use ($useDirectives) { $useDirectives->add(($namespacedPath = $m[1])); }; @@ -453,7 +455,7 @@ LICENSE; $implements = array(); $extends = array(); - $extractor = function($iterator, $callback) { + $extractor = function ($iterator, $callback) { $className = ''; $iterator->seek($iterator->key() + 1); @@ -464,8 +466,7 @@ LICENSE; if (preg_match('/\s?,\s?/', $token)) { $callback(trim($className)); $className = ''; - } - else if ($token == '{') { + } else if ($token == '{') { $callback(trim($className)); return; } @@ -510,13 +511,13 @@ LICENSE; break; case T_IMPLEMENTS: - $extractor($iterator, function($fqn) use (&$implements) { + $extractor($iterator, function ($fqn) use (&$implements) { $implements[] = $fqn; }); break; case T_EXTENDS: - $extractor($iterator, function($fqn) use (&$extends) { + $extractor($iterator, function ($fqn) use (&$extends) { $extends[] = $fqn; }); break; diff --git a/examples/CustomDistributionStrategy.php b/examples/CustomDistributionStrategy.php index 46abf41a..3fe80bfc 100644 --- a/examples/CustomDistributionStrategy.php +++ b/examples/CustomDistributionStrategy.php @@ -37,7 +37,7 @@ class NaiveDistributionStrategy implements DistributionStrategyInterface public function remove($node) { - $this->nodes = array_filter($this->nodes, function($n) use($node) { + $this->nodes = array_filter($this->nodes, function ($n) use ($node) { return $n !== $node; }); @@ -46,8 +46,7 @@ class NaiveDistributionStrategy implements DistributionStrategyInterface public function get($key) { - $count = $this->nodesCount; - if ($count === 0) { + if (0 === $count = $this->nodesCount) { throw new RuntimeException('No connections'); } @@ -61,9 +60,11 @@ class NaiveDistributionStrategy implements DistributionStrategyInterface } $options = array( - 'cluster' => function() { + 'cluster' => function () { $distributor = new NaiveDistributionStrategy(); - return new PredisCluster($distributor); + $cluster = new PredisCluster($distributor); + + return $cluster; }, ); diff --git a/examples/DispatcherLoop.php b/examples/DispatcherLoop.php index dee21d2f..f5b8a990 100644 --- a/examples/DispatcherLoop.php +++ b/examples/DispatcherLoop.php @@ -60,7 +60,7 @@ class EventsListener implements Countable $dispatcher->attachCallback('events', ($events = new EventsListener())); // Attach a function to control the dispatcher loop termination with a message. -$dispatcher->attachCallback('control', function($payload) use ($dispatcher) { +$dispatcher->attachCallback('control', function ($payload) use ($dispatcher) { if ($payload === 'terminate_dispatcher') { $dispatcher->stop(); } diff --git a/examples/MasterSlaveReplicationComplex.php b/examples/MasterSlaveReplicationComplex.php index 8b4ebdd0..802a65b0 100644 --- a/examples/MasterSlaveReplicationComplex.php +++ b/examples/MasterSlaveReplicationComplex.php @@ -50,13 +50,13 @@ $parameters = array( ); $options = array( - 'profile' => function($options) { + 'profile' => function ($options) { $profile = ServerProfile::get('2.6'); $profile->defineCommand('hmgetall', 'HashMultipleGetAll'); return $profile; }, - 'replication' => function($options) { + 'replication' => function ($options) { $replication = new MasterSlaveReplication(); $replication->setScriptReadOnly(HashMultipleGetAll::BODY); diff --git a/examples/MultiExecTransactionsWithCAS.php b/examples/MultiExecTransactionsWithCAS.php index f1634ed2..6450ab81 100644 --- a/examples/MultiExecTransactionsWithCAS.php +++ b/examples/MultiExecTransactionsWithCAS.php @@ -33,7 +33,7 @@ function zpop($client, $key) // which the client bails out with an exception. ); - $client->multiExec($options, function($tx) use ($key, &$element) { + $client->multiExec($options, function ($tx) use ($key, &$element) { @list($element) = $tx->zrange($key, 0, 0); if (isset($element)) { diff --git a/examples/PipelineContext.php b/examples/PipelineContext.php index b10973f1..57fa6384 100644 --- a/examples/PipelineContext.php +++ b/examples/PipelineContext.php @@ -16,7 +16,7 @@ require 'SharedConfigurations.php'; $client = new Predis\Client($single_server); -$replies = $client->pipeline(function($pipe) { +$replies = $client->pipeline(function ($pipe) { $pipe->ping(); $pipe->flushdb(); $pipe->incrby('counter', 10); diff --git a/examples/PubSubContext.php b/examples/PubSubContext.php index 59a823a3..d08eac60 100644 --- a/examples/PubSubContext.php +++ b/examples/PubSubContext.php @@ -38,12 +38,10 @@ foreach ($pubsub as $message) { if ($message->payload == 'quit_loop') { echo "Aborting pubsub loop...\n"; $pubsub->unsubscribe(); - } - else { + } else { echo "Received an unrecognized command: {$message->payload}.\n"; } - } - else { + } else { echo "Received the following message from {$message->channel}:\n", " {$message->payload}\n\n"; } diff --git a/lib/Predis/Autoloader.php b/lib/Predis/Autoloader.php index 54d83fbe..d48635af 100644 --- a/lib/Predis/Autoloader.php +++ b/lib/Predis/Autoloader.php @@ -53,6 +53,7 @@ class Autoloader if (0 === strpos($className, $this->prefix)) { $parts = explode('\\', substr($className, $this->prefixLength)); $filepath = $this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php'; + if (is_file($filepath)) { require($filepath); } diff --git a/lib/Predis/Client.php b/lib/Predis/Client.php index 165603f8..51627b02 100644 --- a/lib/Predis/Client.php +++ b/lib/Predis/Client.php @@ -189,10 +189,9 @@ class Client implements ClientInterface { if (isset($id)) { if (!$this->connection instanceof AggregatedConnectionInterface) { - throw new NotSupportedException( - 'Retrieving connections by alias is supported only with aggregated connections (cluster or replication)' - ); + throw new NotSupportedException('Retrieving connections by alias is supported only with aggregated connections'); } + return $this->connection->getConnectionById($id); } @@ -257,8 +256,7 @@ class Client implements ClientInterface } if ($this->options->exceptions === true) { - $message = $response->getMessage(); - throw new ServerException($message); + throw new ServerException($response->getMessage()); } return $response; diff --git a/lib/Predis/Command/AbstractCommand.php b/lib/Predis/Command/AbstractCommand.php index a8c66dfe..cb848dc6 100644 --- a/lib/Predis/Command/AbstractCommand.php +++ b/lib/Predis/Command/AbstractCommand.php @@ -110,6 +110,7 @@ abstract class AbstractCommand implements CommandInterface if (strlen($argument) > 32) { $argument = substr($argument, 0, 32) . '[...]'; } + $accumulator .= " $argument"; return $accumulator; diff --git a/lib/Predis/Command/Hash/CommandHashStrategy.php b/lib/Predis/Command/Hash/CommandHashStrategy.php index 91aa8577..8c0b457c 100644 --- a/lib/Predis/Command/Hash/CommandHashStrategy.php +++ b/lib/Predis/Command/Hash/CommandHashStrategy.php @@ -317,9 +317,11 @@ class CommandHashStrategy implements CommandHashStrategyInterface for ($i = 1; $i < $count; $i++) { $nextKey = $this->extractKeyTag($keys[$i]); + if ($currentKey !== $nextKey) { return false; } + $currentKey = $nextKey; } @@ -335,10 +337,8 @@ class CommandHashStrategy implements CommandHashStrategyInterface */ protected function extractKeyTag($key) { - $start = strpos($key, '{'); - if ($start !== false) { - $end = strpos($key, '}', $start); - if ($end !== false) { + if (false !== $start = strpos($key, '{')) { + if (false !== $end = strpos($key, '}', $start)) { $key = substr($key, ++$start, $end - $start); } } diff --git a/lib/Predis/Command/HashGetAll.php b/lib/Predis/Command/HashGetAll.php index 58dad44e..9fa7f7a1 100644 --- a/lib/Predis/Command/HashGetAll.php +++ b/lib/Predis/Command/HashGetAll.php @@ -37,6 +37,7 @@ class HashGetAll extends PrefixableCommand } $result = array(); + for ($i = 0; $i < count($data); $i++) { $result[$data[$i]] = $data[++$i]; } diff --git a/lib/Predis/Command/KeySort.php b/lib/Predis/Command/KeySort.php index 2ef07606..0defd7ed 100644 --- a/lib/Predis/Command/KeySort.php +++ b/lib/Predis/Command/KeySort.php @@ -44,20 +44,21 @@ class KeySort extends AbstractCommand implements PrefixableCommandInterface if (isset($sortParams['GET'])) { $getargs = $sortParams['GET']; + if (is_array($getargs)) { foreach ($getargs as $getarg) { $query[] = 'GET'; $query[] = $getarg; } - } - else { + } else { $query[] = 'GET'; $query[] = $getargs; } } - if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT']) - && count($sortParams['LIMIT']) == 2) { + if (isset($sortParams['LIMIT']) && + is_array($sortParams['LIMIT']) && + count($sortParams['LIMIT']) == 2) { $query[] = 'LIMIT'; $query[] = $sortParams['LIMIT'][0]; diff --git a/lib/Predis/Command/ListPopFirstBlocking.php b/lib/Predis/Command/ListPopFirstBlocking.php index 599a41b8..0ada4675 100644 --- a/lib/Predis/Command/ListPopFirstBlocking.php +++ b/lib/Predis/Command/ListPopFirstBlocking.php @@ -34,6 +34,7 @@ class ListPopFirstBlocking extends AbstractCommand implements PrefixableCommandI list($arguments, $timeout) = $arguments; array_push($arguments, $timeout); } + return $arguments; } diff --git a/lib/Predis/Command/Processor/ProcessorChain.php b/lib/Predis/Command/Processor/ProcessorChain.php index e15bc2a4..fb4b109b 100644 --- a/lib/Predis/Command/Processor/ProcessorChain.php +++ b/lib/Predis/Command/Processor/ProcessorChain.php @@ -45,8 +45,7 @@ class ProcessorChain implements CommandProcessorChainInterface, \ArrayAccess */ public function remove(CommandProcessorInterface $processor) { - $index = array_search($processor, $this->processors, true); - if ($index !== false) { + if (false !== $index = array_search($processor, $this->processors, true)) { unset($this[$index]); } } @@ -56,8 +55,7 @@ class ProcessorChain implements CommandProcessorChainInterface, \ArrayAccess */ public function process(CommandInterface $command) { - $count = count($this->processors); - for ($i = 0; $i < $count; $i++) { + for ($i = 0; $i < $count = count($this->processors); $i++) { $this->processors[$i]->process($command); } } diff --git a/lib/Predis/Command/ScriptedCommand.php b/lib/Predis/Command/ScriptedCommand.php index a9ccac94..22371fbc 100644 --- a/lib/Predis/Command/ScriptedCommand.php +++ b/lib/Predis/Command/ScriptedCommand.php @@ -62,8 +62,7 @@ abstract class ScriptedCommand extends ServerEvalSHA { if (false !== $numkeys = $this->getKeysCount()) { $numkeys = $numkeys >= 0 ? $numkeys : count($arguments) + $numkeys; - } - else { + } else { $numkeys = count($arguments); } diff --git a/lib/Predis/Command/ServerBackgroundSave.php b/lib/Predis/Command/ServerBackgroundSave.php index b5f3e065..5993201c 100644 --- a/lib/Predis/Command/ServerBackgroundSave.php +++ b/lib/Predis/Command/ServerBackgroundSave.php @@ -30,10 +30,6 @@ class ServerBackgroundSave extends AbstractCommand */ public function parseResponse($data) { - if ($data == 'Background saving started') { - return true; - } - - return $data; + return $data === 'Background saving started' ? true : $data; } } diff --git a/lib/Predis/Command/ServerClient.php b/lib/Predis/Command/ServerClient.php index b6650d34..54bb3056 100644 --- a/lib/Predis/Command/ServerClient.php +++ b/lib/Predis/Command/ServerClient.php @@ -31,6 +31,7 @@ class ServerClient extends AbstractCommand public function parseResponse($data) { $args = array_change_key_case($this->getArguments(), CASE_UPPER); + switch (strtoupper($args[0])) { case 'LIST': return $this->parseClientList($data); @@ -54,10 +55,12 @@ class ServerClient extends AbstractCommand foreach (explode("\n", $data, -1) as $clientData) { $client = array(); + foreach (explode(' ', $clientData) as $kv) { @list($k, $v) = explode('=', $kv); $client[$k] = $v; } + $clients[] = $client; } diff --git a/lib/Predis/Command/ServerConfig.php b/lib/Predis/Command/ServerConfig.php index 2ca7973a..77a20a37 100644 --- a/lib/Predis/Command/ServerConfig.php +++ b/lib/Predis/Command/ServerConfig.php @@ -40,6 +40,7 @@ class ServerConfig extends AbstractCommand if (is_array($data)) { $result = array(); + for ($i = 0; $i < count($data); $i++) { $result[$data[$i]] = $data[++$i]; } diff --git a/lib/Predis/Command/ServerInfo.php b/lib/Predis/Command/ServerInfo.php index 67d0b47c..6dd351fe 100644 --- a/lib/Predis/Command/ServerInfo.php +++ b/lib/Predis/Command/ServerInfo.php @@ -45,9 +45,9 @@ class ServerInfo extends AbstractCommand $info[$k] = $this->parseAllocationStats($v); continue; } + $info[$k] = $v; - } - else { + } else { $info[$k] = $this->parseDatabaseStats($v); } } @@ -91,6 +91,7 @@ class ServerInfo extends AbstractCommand $size = ">=$objects"; $objects = $extra; } + $stats[$size] = $objects; } diff --git a/lib/Predis/Command/ServerInfoV26x.php b/lib/Predis/Command/ServerInfoV26x.php index e9933cc0..457fe30f 100644 --- a/lib/Predis/Command/ServerInfoV26x.php +++ b/lib/Predis/Command/ServerInfoV26x.php @@ -48,9 +48,9 @@ class ServerInfoV26x extends ServerInfo $current[$k] = $this->parseAllocationStats($v); continue; } + $current[$k] = $v; - } - else { + } else { $current[$k] = $this->parseDatabaseStats($v); } } diff --git a/lib/Predis/Command/ZSetAdd.php b/lib/Predis/Command/ZSetAdd.php index 09fac5a0..569351a4 100644 --- a/lib/Predis/Command/ZSetAdd.php +++ b/lib/Predis/Command/ZSetAdd.php @@ -34,6 +34,7 @@ class ZSetAdd extends PrefixableCommand { if (count($arguments) === 2 && is_array($arguments[1])) { $flattened = array($arguments[0]); + foreach($arguments[1] as $member => $score) { $flattened[] = $score; $flattened[] = $member; diff --git a/lib/Predis/Command/ZSetUnionStore.php b/lib/Predis/Command/ZSetUnionStore.php index 93fa5955..0df8959d 100644 --- a/lib/Predis/Command/ZSetUnionStore.php +++ b/lib/Predis/Command/ZSetUnionStore.php @@ -60,6 +60,7 @@ class ZSetUnionStore extends PrefixableCommand if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) { $finalizedOpts[] = 'WEIGHTS'; + foreach ($opts['WEIGHTS'] as $weight) { $finalizedOpts[] = $weight; } diff --git a/lib/Predis/CommunicationException.php b/lib/Predis/CommunicationException.php index a491a9ca..f4b8687d 100644 --- a/lib/Predis/CommunicationException.php +++ b/lib/Predis/CommunicationException.php @@ -28,11 +28,10 @@ abstract class CommunicationException extends PredisException * @param int $code Error code. * @param \Exception $innerException Inner exception for wrapping the original error. */ - public function __construct(SingleConnectionInterface $connection, - $message = null, $code = null, \Exception $innerException = null) - { + public function __construct( + SingleConnectionInterface $connection, $message = null, $code = null, \Exception $innerException = null + ) { parent::__construct($message, $code, $innerException); - $this->connection = $connection; } diff --git a/lib/Predis/Connection/AbstractConnection.php b/lib/Predis/Connection/AbstractConnection.php index 7176b316..d27ca376 100644 --- a/lib/Predis/Connection/AbstractConnection.php +++ b/lib/Predis/Connection/AbstractConnection.php @@ -92,6 +92,7 @@ abstract class AbstractConnection implements SingleConnectionInterface if ($this->isConnected()) { throw new ClientException('Connection already estabilished'); } + $this->resource = $this->createResource(); } diff --git a/lib/Predis/Connection/ComposableStreamConnection.php b/lib/Predis/Connection/ComposableStreamConnection.php index 12fb86c6..575ea0e2 100644 --- a/lib/Predis/Connection/ComposableStreamConnection.php +++ b/lib/Predis/Connection/ComposableStreamConnection.php @@ -46,6 +46,7 @@ class ComposableStreamConnection extends StreamConnection implements ComposableC if ($protocol === null) { throw new \InvalidArgumentException("The protocol instance cannot be a null value"); } + $this->protocol = $protocol; } @@ -79,12 +80,13 @@ class ComposableStreamConnection extends StreamConnection implements ComposableC do { $chunk = fread($socket, $length); + if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading bytes from the server'); } + $value .= $chunk; - } - while (($length -= strlen($chunk)) > 0); + } while (($length -= strlen($chunk)) > 0); return $value; } @@ -99,12 +101,13 @@ class ComposableStreamConnection extends StreamConnection implements ComposableC do { $chunk = fgets($socket); + if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server'); } + $value .= $chunk; - } - while (substr($value, -2) !== "\r\n"); + } while (substr($value, -2) !== "\r\n"); return substr($value, 0, -2); } diff --git a/lib/Predis/Connection/ConnectionFactory.php b/lib/Predis/Connection/ConnectionFactory.php index 55ce65e0..dbf5247f 100644 --- a/lib/Predis/Connection/ConnectionFactory.php +++ b/lib/Predis/Connection/ConnectionFactory.php @@ -97,11 +97,13 @@ class ConnectionFactory implements ConnectionFactoryInterface } $scheme = $parameters->scheme; + if (!isset($this->schemes[$scheme])) { throw new \InvalidArgumentException("Unknown connection scheme: $scheme"); } $initializer = $this->schemes[$scheme]; + if (!is_callable($initializer)) { $connection = new $initializer($parameters); $this->prepareConnection($connection, $profile ?: ServerProfile::getDefault()); @@ -110,6 +112,7 @@ class ConnectionFactory implements ConnectionFactoryInterface } $connection = call_user_func($initializer, $parameters, $profile); + if (!$connection instanceof SingleConnectionInterface) { throw new \InvalidArgumentException( 'Objects returned by connection initializers must implement ' . diff --git a/lib/Predis/Connection/ConnectionParameters.php b/lib/Predis/Connection/ConnectionParameters.php index d863ca99..bc122b3a 100644 --- a/lib/Predis/Connection/ConnectionParameters.php +++ b/lib/Predis/Connection/ConnectionParameters.php @@ -124,6 +124,7 @@ class ConnectionParameters implements ConnectionParametersInterface @list($k, $v) = explode('=', $kv); $parsed[$k] = $v; } + unset($parsed['query']); } @@ -140,6 +141,7 @@ class ConnectionParameters implements ConnectionParametersInterface { if (count($parameters) > 0) { $casters = array_intersect_key($this->getValueCasters(), $parameters); + foreach ($casters as $parameter => $caster) { $parameters[$parameter] = call_user_func($caster, $parameters[$parameter]); } diff --git a/lib/Predis/Connection/MasterSlaveReplication.php b/lib/Predis/Connection/MasterSlaveReplication.php index f85d731d..4d5cda76 100644 --- a/lib/Predis/Connection/MasterSlaveReplication.php +++ b/lib/Predis/Connection/MasterSlaveReplication.php @@ -66,8 +66,7 @@ class MasterSlaveReplication implements ReplicationConnectionInterface if ($alias === 'master') { $this->master = $connection; - } - else { + } else { $this->slaves[$alias ?: count($this->slaves)] = $connection; } @@ -84,8 +83,7 @@ class MasterSlaveReplication implements ReplicationConnectionInterface $this->reset(); return true; - } - else { + } else { if (($id = array_search($connection, $this->slaves, true)) !== false) { unset($this->slaves[$id]); $this->reset(); @@ -108,7 +106,6 @@ class MasterSlaveReplication implements ReplicationConnectionInterface return $this->current; } - if ($this->current === $this->master) { return $this->current; } @@ -128,6 +125,7 @@ class MasterSlaveReplication implements ReplicationConnectionInterface if ($connectionId === 'master') { return $this->master; } + if (isset($this->slaves[$connectionId])) { return $this->slaves[$connectionId]; } @@ -215,6 +213,7 @@ class MasterSlaveReplication implements ReplicationConnectionInterface if ($this->master) { $this->master->disconnect(); } + foreach ($this->slaves as $connection) { $connection->disconnect(); } @@ -308,8 +307,7 @@ class MasterSlaveReplication implements ReplicationConnectionInterface if ($readonly) { $this->readonly[$commandID] = $readonly; - } - else { + } else { unset($this->readonly[$commandID]); } } @@ -330,8 +328,7 @@ class MasterSlaveReplication implements ReplicationConnectionInterface if ($readonly) { $this->readonlySHA1[$sha1] = $readonly; - } - else { + } else { unset($this->readonlySHA1[$sha1]); } } diff --git a/lib/Predis/Connection/PhpiredisConnection.php b/lib/Predis/Connection/PhpiredisConnection.php index a237fe9b..5330be37 100644 --- a/lib/Predis/Connection/PhpiredisConnection.php +++ b/lib/Predis/Connection/PhpiredisConnection.php @@ -120,7 +120,7 @@ class PhpiredisConnection extends AbstractConnection */ private function getStatusHandler() { - return function($payload) { + return function ($payload) { switch ($payload) { case 'OK': return true; @@ -142,7 +142,7 @@ class PhpiredisConnection extends AbstractConnection */ private function getErrorHandler() { - return function($errorMessage) { + return function ($errorMessage) { return new ResponseError($errorMessage); }; } @@ -294,6 +294,7 @@ class PhpiredisConnection extends AbstractConnection parent::connect(); $this->connectWithTimeout($this->parameters); + if (count($this->initCmds) > 0) { $this->sendInitializationCommands(); } @@ -306,7 +307,6 @@ class PhpiredisConnection extends AbstractConnection { if ($this->isConnected()) { socket_close($this->getResource()); - parent::disconnect(); } } @@ -363,8 +363,7 @@ class PhpiredisConnection extends AbstractConnection if ($state === PHPIREDIS_READER_STATE_COMPLETE) { return phpiredis_reader_get_reply($reader); - } - else { + } else { $this->onProtocolError(phpiredis_reader_get_error($reader)); } } diff --git a/lib/Predis/Connection/PredisCluster.php b/lib/Predis/Connection/PredisCluster.php index 878cc214..17f29440 100644 --- a/lib/Predis/Connection/PredisCluster.php +++ b/lib/Predis/Connection/PredisCluster.php @@ -84,8 +84,7 @@ class PredisCluster implements ClusterConnectionInterface, \IteratorAggregate, \ if (isset($parameters->alias)) { $this->pool[$parameters->alias] = $connection; - } - else { + } else { $this->pool[] = $connection; } diff --git a/lib/Predis/Connection/RedisCluster.php b/lib/Predis/Connection/RedisCluster.php index 111cf610..df31800e 100644 --- a/lib/Predis/Connection/RedisCluster.php +++ b/lib/Predis/Connection/RedisCluster.php @@ -90,6 +90,7 @@ class RedisCluster implements ClusterConnectionInterface, \IteratorAggregate, \C { if (($id = array_search($connection, $this->pool, true)) !== false) { unset($this->pool[$id]); + return true; } @@ -106,6 +107,7 @@ class RedisCluster implements ClusterConnectionInterface, \IteratorAggregate, \C { if (isset($this->pool[$connectionId])) { unset($this->pool[$connectionId]); + return true; } @@ -126,6 +128,7 @@ class RedisCluster implements ClusterConnectionInterface, \IteratorAggregate, \C } $slot = $hash & 0x0FFF; + if (isset($this->slots[$slot])) { return $this->slots[$slot]; } diff --git a/lib/Predis/Connection/StreamConnection.php b/lib/Predis/Connection/StreamConnection.php index edae78fb..7f645631 100644 --- a/lib/Predis/Connection/StreamConnection.php +++ b/lib/Predis/Connection/StreamConnection.php @@ -78,8 +78,8 @@ class StreamConnection extends AbstractConnection private function tcpStreamInitializer(ConnectionParametersInterface $parameters) { $uri = "tcp://{$parameters->host}:{$parameters->port}/"; - $flags = STREAM_CLIENT_CONNECT; + if (isset($parameters->async_connect) && $parameters->async_connect === true) { $flags |= STREAM_CLIENT_ASYNC_CONNECT; } @@ -87,9 +87,7 @@ class StreamConnection extends AbstractConnection $flags |= STREAM_CLIENT_PERSISTENT; } - $resource = @stream_socket_client( - $uri, $errno, $errstr, $parameters->timeout, $flags - ); + $resource = @stream_socket_client($uri, $errno, $errstr, $parameters->timeout, $flags); if (!$resource) { $this->onConnectionError(trim($errstr), $errno); @@ -115,15 +113,13 @@ class StreamConnection extends AbstractConnection private function unixStreamInitializer(ConnectionParametersInterface $parameters) { $uri = "unix://{$parameters->path}"; - $flags = STREAM_CLIENT_CONNECT; + if ($parameters->persistent === true) { $flags |= STREAM_CLIENT_PERSISTENT; } - $resource = @stream_socket_client( - $uri, $errno, $errstr, $parameters->timeout, $flags - ); + $resource = @stream_socket_client($uri, $errno, $errstr, $parameters->timeout, $flags); if (!$resource) { $this->onConnectionError(trim($errstr), $errno); @@ -151,7 +147,6 @@ class StreamConnection extends AbstractConnection { if ($this->isConnected()) { fclose($this->getResource()); - parent::disconnect(); } } @@ -181,12 +176,14 @@ class StreamConnection extends AbstractConnection while (($length = strlen($buffer)) > 0) { $written = fwrite($socket, $buffer); + if ($length === $written) { return; } if ($written === false || $written === 0) { $this->onConnectionError('Error while writing bytes to the server'); } + $buffer = substr($buffer, $written); } } @@ -196,8 +193,8 @@ class StreamConnection extends AbstractConnection */ public function read() { $socket = $this->getResource(); - $chunk = fgets($socket); + if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server'); } @@ -229,11 +226,11 @@ class StreamConnection extends AbstractConnection do { $chunk = fread($socket, min($bytesLeft, 4096)); + if ($chunk === false || $chunk === '') { - $this->onConnectionError( - 'Error while reading bytes from the server' - ); + $this->onConnectionError('Error while reading bytes from the server'); } + $bulkData .= $chunk; $bytesLeft = $size - strlen($bulkData); } while ($bytesLeft > 0); @@ -242,15 +239,16 @@ class StreamConnection extends AbstractConnection case '*': // multi bulk $count = (int) $payload; + if ($count === -1) { return null; } - if ($this->mbiterable === true) { return new MultiBulkResponseSimple($this, $count); } $multibulk = array(); + for ($i = 0; $i < $count; $i++) { $multibulk[$i] = $this->read(); } diff --git a/lib/Predis/Connection/WebdisConnection.php b/lib/Predis/Connection/WebdisConnection.php index d365bde8..0fe2a31a 100644 --- a/lib/Predis/Connection/WebdisConnection.php +++ b/lib/Predis/Connection/WebdisConnection.php @@ -94,6 +94,7 @@ class WebdisConnection implements SingleConnectionInterface if (!function_exists('curl_init')) { throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'curl')); } + if (!function_exists('phpiredis_reader_create')) { throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'phpiredis')); } @@ -120,8 +121,7 @@ class WebdisConnection implements SingleConnectionInterface $options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}"; } - $resource = curl_init(); - curl_setopt_array($resource, $options); + curl_setopt_array($resource = curl_init(), $options); return $resource; } @@ -149,7 +149,7 @@ class WebdisConnection implements SingleConnectionInterface */ protected function getStatusHandler() { - return function($payload) { + return function ($payload) { return $payload === 'OK' ? true : $payload; }; } @@ -161,7 +161,7 @@ class WebdisConnection implements SingleConnectionInterface */ protected function getErrorHandler() { - return function($errorMessage) { + return function ($errorMessage) { return new ResponseError($errorMessage); }; } @@ -255,8 +255,7 @@ class WebdisConnection implements SingleConnectionInterface if ($arguments = $command->getArguments()) { $arguments = implode('/', array_map('urlencode', $arguments)); $serializedCommand = "$commandId/$arguments.raw"; - } - else { + } else { $serializedCommand = "$commandId.raw"; } @@ -272,14 +271,14 @@ class WebdisConnection implements SingleConnectionInterface if ($readerState === PHPIREDIS_READER_STATE_COMPLETE) { $reply = phpiredis_reader_get_reply($this->reader); + if ($reply instanceof ResponseObjectInterface) { return $reply; } + return $command->parseResponse($reply); - } - else { - $error = phpiredis_reader_get_error($this->reader); - throw new ProtocolException($this, $error); + } else { + throw new ProtocolException($this, phpiredis_reader_get_error($this->reader)); } } diff --git a/lib/Predis/Distribution/HashRing.php b/lib/Predis/Distribution/HashRing.php index a72f51b8..5781831e 100644 --- a/lib/Predis/Distribution/HashRing.php +++ b/lib/Predis/Distribution/HashRing.php @@ -36,7 +36,7 @@ class HashRing implements DistributionStrategyInterface public function __construct($replicas = self::DEFAULT_REPLICAS) { $this->replicas = $replicas; - $this->nodes = array(); + $this->nodes = array(); } /** @@ -101,6 +101,7 @@ class HashRing implements DistributionStrategyInterface private function computeTotalWeight() { $totalWeight = 0; + foreach ($this->nodes as $node) { $totalWeight += $node['weight']; } @@ -123,14 +124,14 @@ class HashRing implements DistributionStrategyInterface $this->ring = array(); $totalWeight = $this->computeTotalWeight(); - $nodesCount = count($this->nodes); + $nodesCount = count($this->nodes); foreach ($this->nodes as $node) { $weightRatio = $node['weight'] / $totalWeight; $this->addNodeToRing($this->ring, $node, $nodesCount, $this->replicas, $weightRatio); } - ksort($this->ring, SORT_NUMERIC); + ksort($this->ring, SORT_NUMERIC); $this->ringKeys = array_keys($this->ring); $this->ringKeysCount = count($this->ringKeys); } @@ -199,13 +200,12 @@ class HashRing implements DistributionStrategyInterface while ($lower <= $upper) { $index = ($lower + $upper) >> 1; $item = $ringKeys[$index]; + if ($item > $key) { $upper = $index - 1; - } - else if ($item < $key) { + } else if ($item < $key) { $lower = $index + 1; - } - else { + } else { return $item; } } diff --git a/lib/Predis/Distribution/KetamaPureRing.php b/lib/Predis/Distribution/KetamaPureRing.php index 3dbd2cd6..cc31a5dc 100644 --- a/lib/Predis/Distribution/KetamaPureRing.php +++ b/lib/Predis/Distribution/KetamaPureRing.php @@ -42,6 +42,7 @@ class KetamaPureRing extends HashRing for ($i = 0; $i < $replicas; $i++) { $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true)); + foreach ($unpackedDigest as $key) { $ring[$key] = $nodeObject; } diff --git a/lib/Predis/Helpers.php b/lib/Predis/Helpers.php index 5cd57d58..4e06cd98 100644 --- a/lib/Predis/Helpers.php +++ b/lib/Predis/Helpers.php @@ -32,6 +32,7 @@ class Helpers { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); + if ($connection->isConnected()) { $connection->disconnect(); } diff --git a/lib/Predis/Iterator/MultiBulkResponseSimple.php b/lib/Predis/Iterator/MultiBulkResponseSimple.php index c93d82ae..b3448376 100644 --- a/lib/Predis/Iterator/MultiBulkResponseSimple.php +++ b/lib/Predis/Iterator/MultiBulkResponseSimple.php @@ -29,9 +29,9 @@ class MultiBulkResponseSimple extends MultiBulkResponse public function __construct(SingleConnectionInterface $connection, $size) { $this->connection = $connection; - $this->position = 0; - $this->current = $size > 0 ? $this->getValue() : null; - $this->replySize = $size; + $this->position = 0; + $this->current = $size > 0 ? $this->getValue() : null; + $this->replySize = $size; } /** @@ -59,8 +59,7 @@ class MultiBulkResponseSimple extends MultiBulkResponse $this->position = $this->replySize; $this->connection->disconnect(); } - } - else { + } else { while ($this->valid()) { $this->next(); } diff --git a/lib/Predis/Monitor/MonitorContext.php b/lib/Predis/Monitor/MonitorContext.php index 572ca1b2..1c0bf17b 100644 --- a/lib/Predis/Monitor/MonitorContext.php +++ b/lib/Predis/Monitor/MonitorContext.php @@ -55,7 +55,6 @@ class MonitorContext implements \Iterator if ($client->getConnection() instanceof AggregatedConnectionInterface) { throw new NotSupportedException('Cannot initialize a monitor context when using aggregated connections'); } - if ($client->getProfile()->supportsCommand('monitor') === false) { throw new NotSupportedException('The current profile does not support the MONITOR command'); } @@ -137,16 +136,18 @@ class MonitorContext implements \Iterator $client = null; $event = $this->client->getConnection()->read(); - $callback = function($matches) use (&$database, &$client) { + $callback = function ($matches) use (&$database, &$client) { if (2 === $count = count($matches)) { // Redis <= 2.4 $database = (int) $matches[1]; } + if (4 === $count) { // Redis >= 2.6 $database = (int) $matches[2]; $client = $matches[3]; } + return ' '; }; diff --git a/lib/Predis/Option/ClientCluster.php b/lib/Predis/Option/ClientCluster.php index 00b03c9e..e0191c24 100644 --- a/lib/Predis/Option/ClientCluster.php +++ b/lib/Predis/Option/ClientCluster.php @@ -45,6 +45,7 @@ class ClientCluster extends AbstractOption if (is_callable($value)) { return $this->checkInstance(call_user_func($value, $options)); } + $initializer = $this->getInitializer($options, $value); return $this->checkInstance($initializer()); @@ -61,12 +62,12 @@ class ClientCluster extends AbstractOption { switch ($fqnOrType) { case 'predis': - return function() { + return function () { return new PredisCluster(); }; case 'redis': - return function() use($options) { + return function () use ($options) { $connectionFactory = $options->connections; $cluster = new RedisCluster($connectionFactory); @@ -78,7 +79,7 @@ class ClientCluster extends AbstractOption if (is_string($fqnOrType) && !class_exists($fqnOrType)) { throw new \InvalidArgumentException("Class $fqnOrType does not exist"); } - return function() use($fqnOrType) { + return function () use ($fqnOrType) { return new $fqnOrType(); }; } diff --git a/lib/Predis/Option/ClientConnectionFactory.php b/lib/Predis/Option/ClientConnectionFactory.php index 841f2119..ce1eab7b 100644 --- a/lib/Predis/Option/ClientConnectionFactory.php +++ b/lib/Predis/Option/ClientConnectionFactory.php @@ -31,15 +31,18 @@ class ClientConnectionFactory extends AbstractOption } if (is_array($value)) { $factory = $this->getDefault($options); + foreach ($value as $scheme => $initializer) { $factory->define($scheme, $initializer); } + return $factory; } if (is_string($value) && class_exists($value)) { if (!($factory = new $value()) && !$factory instanceof ConnectionFactoryInterface) { throw new \InvalidArgumentException("Class $value must be an instance of Predis\Connection\ConnectionFactoryInterface"); } + return $factory; } diff --git a/lib/Predis/Option/ClientOptions.php b/lib/Predis/Option/ClientOptions.php index f75a11a5..bf88cb9e 100644 --- a/lib/Predis/Option/ClientOptions.php +++ b/lib/Predis/Option/ClientOptions.php @@ -61,11 +61,10 @@ class ClientOptions implements ClientOptionsInterface foreach ($options as $option => $value) { if (isset($handlers[$option])) { $handler = $handlers[$option]; - $handlers[$option] = function($options) use($handler, $value) { + $handlers[$option] = function ($options) use ($handler, $value) { return $handler->filter($options, $value); }; - } - else { + } else { $this->options[$option] = $value; } } diff --git a/lib/Predis/Option/ClientProfile.php b/lib/Predis/Option/ClientProfile.php index 8eaebd13..7b97347a 100644 --- a/lib/Predis/Option/ClientProfile.php +++ b/lib/Predis/Option/ClientProfile.php @@ -28,6 +28,7 @@ class ClientProfile extends AbstractOption { if (is_string($value)) { $value = ServerProfile::get($value); + if (isset($options->prefix)) { $value->setProcessor($options->prefix); } @@ -50,6 +51,7 @@ class ClientProfile extends AbstractOption public function getDefault(ClientOptionsInterface $options) { $profile = ServerProfile::getDefault(); + if (isset($options->prefix)) { $profile->setProcessor($options->prefix); } diff --git a/lib/Predis/Option/ClientReplication.php b/lib/Predis/Option/ClientReplication.php index f4420adc..f1c6367b 100644 --- a/lib/Predis/Option/ClientReplication.php +++ b/lib/Predis/Option/ClientReplication.php @@ -43,9 +43,11 @@ class ClientReplication extends AbstractOption { if (is_callable($value)) { $connection = call_user_func($value, $options); + if (!$connection instanceof ReplicationConnectionInterface) { throw new \InvalidArgumentException('Instance of Predis\Connection\ReplicationConnectionInterface expected'); } + return $connection; } @@ -53,9 +55,11 @@ class ClientReplication extends AbstractOption if (!class_exists($value)) { throw new \InvalidArgumentException("Class $value does not exist"); } + if (!($connection = new $value()) instanceof ReplicationConnectionInterface) { throw new \InvalidArgumentException('Instance of Predis\Connection\ReplicationConnectionInterface expected'); } + return $connection; } diff --git a/lib/Predis/Option/CustomOption.php b/lib/Predis/Option/CustomOption.php index dac29f39..5c96b86a 100644 --- a/lib/Predis/Option/CustomOption.php +++ b/lib/Predis/Option/CustomOption.php @@ -27,7 +27,7 @@ class CustomOption implements OptionInterface public function __construct(Array $options = array()) { $this->filter = $this->ensureCallable($options, 'filter'); - $this->default = $this->ensureCallable($options, 'default'); + $this->default = $this->ensureCallable($options, 'default'); } /** @@ -42,8 +42,7 @@ class CustomOption implements OptionInterface return; } - $callable = $options[$key]; - if (is_callable($callable)) { + if (is_callable($callable = $options[$key])) { return $callable; } @@ -59,9 +58,8 @@ class CustomOption implements OptionInterface if ($this->filter === null) { return $value; } - $validator = $this->filter; - return $validator($options, $value); + return call_user_func($this->filter, $options, $value); } } @@ -73,9 +71,8 @@ class CustomOption implements OptionInterface if (!isset($this->default)) { return; } - $default = $this->default; - return $default($options); + return call_user_func($this->default, $options); } /** diff --git a/lib/Predis/Pipeline/MultiExecExecutor.php b/lib/Predis/Pipeline/MultiExecExecutor.php index 06984fdc..06af2c38 100644 --- a/lib/Predis/Pipeline/MultiExecExecutor.php +++ b/lib/Predis/Pipeline/MultiExecExecutor.php @@ -98,7 +98,6 @@ class MultiExecExecutor implements PipelineExecutorInterface if ($response = $responses[$i] instanceof \Iterator) { $response = iterator_to_array($response); } - $values[$i] = $commands->dequeue()->parseResponse($responses[$i]); unset($responses[$i]); } diff --git a/lib/Predis/Pipeline/PipelineContext.php b/lib/Predis/Pipeline/PipelineContext.php index 102d9951..33dedd24 100644 --- a/lib/Predis/Pipeline/PipelineContext.php +++ b/lib/Predis/Pipeline/PipelineContext.php @@ -109,10 +109,8 @@ class PipelineContext implements BasicClientInterface, ExecutableContextInterfac if ($send && !$this->pipeline->isEmpty()) { $connection = $this->client->getConnection(); $replies = $this->executor->execute($connection, $this->pipeline); - $this->replies = array_merge($this->replies, $replies); - } - else { + } else { $this->pipeline = new SplQueue(); } @@ -130,6 +128,7 @@ class PipelineContext implements BasicClientInterface, ExecutableContextInterfac if ($bool === true && $this->running === true) { throw new ClientException("This pipeline is already opened"); } + $this->running = $bool; } @@ -153,8 +152,7 @@ class PipelineContext implements BasicClientInterface, ExecutableContextInterfac call_user_func($callable, $this); } $this->flushPipeline(); - } - catch (\Exception $exception) { + } catch (\Exception $exception) { $pipelineBlockException = $exception; } diff --git a/lib/Predis/Pipeline/SafeClusterExecutor.php b/lib/Predis/Pipeline/SafeClusterExecutor.php index efaf4967..b3622309 100644 --- a/lib/Predis/Pipeline/SafeClusterExecutor.php +++ b/lib/Predis/Pipeline/SafeClusterExecutor.php @@ -42,8 +42,7 @@ class SafeClusterExecutor implements PipelineExecutorInterface try { $cmdConnection->writeCommand($command); - } - catch (CommunicationException $exception) { + } catch (CommunicationException $exception) { $connectionExceptions[spl_object_hash($cmdConnection)] = $exception; } } @@ -62,8 +61,7 @@ class SafeClusterExecutor implements PipelineExecutorInterface try { $response = $cmdConnection->readResponse($command); $values[$i] = $response instanceof \Iterator ? iterator_to_array($response) : $response; - } - catch (CommunicationException $exception) { + } catch (CommunicationException $exception) { $values[$i] = $exception; $connectionExceptions[$connectionObjectHash] = $exception; } diff --git a/lib/Predis/Pipeline/SafeExecutor.php b/lib/Predis/Pipeline/SafeExecutor.php index 4fa1420e..fb95d899 100644 --- a/lib/Predis/Pipeline/SafeExecutor.php +++ b/lib/Predis/Pipeline/SafeExecutor.php @@ -35,8 +35,7 @@ class SafeExecutor implements PipelineExecutorInterface foreach ($commands as $command) { try { $connection->writeCommand($command); - } - catch (CommunicationException $exception) { + } catch (CommunicationException $exception) { return array_fill(0, $size, $exception); } } @@ -47,8 +46,7 @@ class SafeExecutor implements PipelineExecutorInterface try { $response = $connection->readResponse($command); $values[$i] = $response instanceof \Iterator ? iterator_to_array($response) : $response; - } - catch (CommunicationException $exception) { + } catch (CommunicationException $exception) { $toAdd = count($commands) - count($values); $values = array_merge($values, array_fill(0, $toAdd, $exception)); break; diff --git a/lib/Predis/Profile/ServerProfile.php b/lib/Predis/Profile/ServerProfile.php index edd7c6b0..82d14a70 100644 --- a/lib/Predis/Profile/ServerProfile.php +++ b/lib/Predis/Profile/ServerProfile.php @@ -114,6 +114,7 @@ abstract class ServerProfile implements ServerProfileInterface, CommandProcessin if (!isset(self::$profiles)) { self::$profiles = self::getDefaultProfiles(); } + if (!isset(self::$profiles[$version])) { throw new ClientException("Unknown server profile: $version"); } @@ -165,6 +166,7 @@ abstract class ServerProfile implements ServerProfileInterface, CommandProcessin public function createCommand($method, $arguments = array()) { $method = strtolower($method); + if (!isset($this->commands[$method])) { throw new ClientException("'$method' is not a registered Redis command"); } @@ -189,9 +191,11 @@ abstract class ServerProfile implements ServerProfileInterface, CommandProcessin public function defineCommand($alias, $command) { $commandReflection = new \ReflectionClass($command); + if (!$commandReflection->isSubclassOf('Predis\Command\CommandInterface')) { throw new \InvalidArgumentException("Cannot register '$command' as it is not a valid Redis command"); } + $this->commands[strtolower($alias)] = $command; } diff --git a/lib/Predis/Profile/ServerVersionNext.php b/lib/Predis/Profile/ServerVersionNext.php index 8a80694b..695388ab 100644 --- a/lib/Predis/Profile/ServerVersionNext.php +++ b/lib/Predis/Profile/ServerVersionNext.php @@ -31,7 +31,6 @@ class ServerVersionNext extends ServerVersion26 */ public function getSupportedCommands() { - return array_merge(parent::getSupportedCommands(), array( - )); + return array_merge(parent::getSupportedCommands(), array()); } } diff --git a/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php b/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php index 3d29f237..47f23d4c 100644 --- a/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php +++ b/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php @@ -58,8 +58,7 @@ class ResponseMultiBulkHandler implements ResponseHandlerInterface if (isset($handlersCache[$prefix])) { $handler = $handlersCache[$prefix]; - } - else { + } else { $handler = $reader->getHandler($prefix); $handlersCache[$prefix] = $handler; } diff --git a/lib/Predis/Protocol/Text/TextProtocol.php b/lib/Predis/Protocol/Text/TextProtocol.php index c52e97e0..a303e6fd 100644 --- a/lib/Predis/Protocol/Text/TextProtocol.php +++ b/lib/Predis/Protocol/Text/TextProtocol.php @@ -103,6 +103,7 @@ class TextProtocol implements ProtocolInterface } $multibulk = array(); + for ($i = 0; $i < $count; $i++) { $multibulk[$i] = $this->read($connection); } diff --git a/lib/Predis/Protocol/Text/TextResponseReader.php b/lib/Predis/Protocol/Text/TextResponseReader.php index 6d767d98..7a5e3de8 100644 --- a/lib/Predis/Protocol/Text/TextResponseReader.php +++ b/lib/Predis/Protocol/Text/TextResponseReader.php @@ -83,11 +83,13 @@ class TextResponseReader implements ResponseReaderInterface public function read(ComposableConnectionInterface $connection) { $header = $connection->readLine(); + if ($header === '') { $this->protocolError($connection, 'Unexpected empty header'); } $prefix = $header[0]; + if (!isset($this->handlers[$prefix])) { $this->protocolError($connection, "Unknown prefix '$prefix'"); } diff --git a/lib/Predis/PubSub/AbstractPubSubContext.php b/lib/Predis/PubSub/AbstractPubSubContext.php index ab45bf95..a9930971 100644 --- a/lib/Predis/PubSub/AbstractPubSubContext.php +++ b/lib/Predis/PubSub/AbstractPubSubContext.php @@ -115,8 +115,7 @@ abstract class AbstractPubSubContext implements \Iterator if ($force) { $this->invalidate(); $this->disconnect(); - } - else { + } else { if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) { $this->unsubscribe(); } diff --git a/lib/Predis/PubSub/DispatcherLoop.php b/lib/Predis/PubSub/DispatcherLoop.php index 3f6796d0..e2455a00 100644 --- a/lib/Predis/PubSub/DispatcherLoop.php +++ b/lib/Predis/PubSub/DispatcherLoop.php @@ -69,6 +69,7 @@ class DispatcherLoop if (isset($callable)) { $this->validateCallback($callable); } + $this->subscriptionCallback = $callable; } @@ -83,6 +84,7 @@ class DispatcherLoop if (isset($callable)) { $this->validateCallback($callable); } + $this->subscriptionCallback = $callable; } @@ -125,14 +127,14 @@ class DispatcherLoop $callback = $this->subscriptionCallback; call_user_func($callback, $message); } + continue; } if (isset($this->callbacks[$message->channel])) { $callback = $this->callbacks[$message->channel]; call_user_func($callback, $message->payload); - } - else if (isset($this->defaultCallback)) { + } else if (isset($this->defaultCallback)) { $callback = $this->defaultCallback; call_user_func($callback, $message); } diff --git a/lib/Predis/PubSub/PubSubContext.php b/lib/Predis/PubSub/PubSubContext.php index ef3e6383..6f53af37 100644 --- a/lib/Predis/PubSub/PubSubContext.php +++ b/lib/Predis/PubSub/PubSubContext.php @@ -54,6 +54,7 @@ class PubSubContext extends AbstractPubSubContext } $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe'); + if ($client->getProfile()->supportsCommands($commands) === false) { throw new NotSupportedException('The current profile does not support PUB/SUB related commands'); } diff --git a/lib/Predis/ServerException.php b/lib/Predis/ServerException.php index 4c1bfad8..0a60c7e4 100644 --- a/lib/Predis/ServerException.php +++ b/lib/Predis/ServerException.php @@ -26,6 +26,7 @@ class ServerException extends PredisException implements ResponseErrorInterface public function getErrorType() { list($errorType, ) = explode(' ', $this->getMessage(), 2); + return $errorType; } diff --git a/lib/Predis/Transaction/AbortedMultiExecException.php b/lib/Predis/Transaction/AbortedMultiExecException.php index 58e46845..bccaa870 100644 --- a/lib/Predis/Transaction/AbortedMultiExecException.php +++ b/lib/Predis/Transaction/AbortedMultiExecException.php @@ -30,7 +30,6 @@ class AbortedMultiExecException extends PredisException public function __construct(MultiExecContext $transaction, $message, $code = null) { parent::__construct($message, $code); - $this->transaction = $transaction; } diff --git a/lib/Predis/Transaction/MultiExecContext.php b/lib/Predis/Transaction/MultiExecContext.php index 82d86d7a..58f3f48b 100644 --- a/lib/Predis/Transaction/MultiExecContext.php +++ b/lib/Predis/Transaction/MultiExecContext.php @@ -122,6 +122,7 @@ class MultiExecContext implements BasicClientInterface, ExecutableContextInterfa } $profile = $client->getProfile(); + if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) { throw new NotSupportedException('The current profile does not support MULTI, EXEC and DISCARD'); } @@ -171,6 +172,7 @@ class MultiExecContext implements BasicClientInterface, ExecutableContextInterfa if (!$cas || ($cas && $discarded)) { $this->client->multi(); + if ($discarded) { $this->unflagState(self::STATE_CAS); } @@ -204,12 +206,12 @@ class MultiExecContext implements BasicClientInterface, ExecutableContextInterfa public function executeCommand(CommandInterface $command) { $this->initialize(); - $response = $this->client->executeCommand($command); if ($this->checkState(self::STATE_CAS)) { return $response; } + if (!$response instanceof ResponseQueued) { $this->onProtocolError('The server did not respond with a QUEUED status reply'); } @@ -249,8 +251,7 @@ class MultiExecContext implements BasicClientInterface, ExecutableContextInterfa if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) { $this->unflagState(self::STATE_CAS); $this->client->multi(); - } - else { + } else { $this->initialize(); } @@ -350,6 +351,7 @@ class MultiExecContext implements BasicClientInterface, ExecutableContextInterfa if ($this->checkState(self::STATE_WATCH)) { $this->discard(); } + return; } @@ -414,14 +416,11 @@ class MultiExecContext implements BasicClientInterface, ExecutableContextInterfa try { call_user_func($callable, $this); - } - catch (CommunicationException $exception) { + } catch (CommunicationException $exception) { $blockException = $exception; - } - catch (ServerException $exception) { + } catch (ServerException $exception) { $blockException = $exception; - } - catch (\Exception $exception) { + } catch (\Exception $exception) { $blockException = $exception; $this->discard(); } diff --git a/tests/Predis/ClientTest.php b/tests/Predis/ClientTest.php index 372ec313..ce1c629e 100644 --- a/tests/Predis/ClientTest.php +++ b/tests/Predis/ClientTest.php @@ -432,7 +432,7 @@ class ClientTest extends StandardTestCase /** * @group disconnected * @expectedException Predis\NotSupportedException - * @expectedExceptionMessage Retrieving connections by alias is supported only with aggregated connections (cluster or replication) + * @expectedExceptionMessage Retrieving connections by alias is supported only with aggregated connections */ public function testGetConnectionWithAliasWorksOnlyWithCluster() { @@ -491,7 +491,7 @@ class ClientTest extends StandardTestCase $options = array('executor' => $executor); $test = $this; - $mockCallback = function($pipeline) use($executor, $test) { + $mockCallback = function ($pipeline) use ($executor, $test) { $reflection = new \ReflectionProperty($pipeline, 'executor'); $reflection->setAccessible(true); @@ -602,7 +602,9 @@ class ClientTest extends StandardTestCase ->method('executeCommand') ->will($this->returnValue(new ResponseQueued())); - $txCallback = function($tx) { $tx->ping(); }; + $txCallback = function ($tx) { + $tx->ping(); + }; $callable = $this->getMock('stdClass', array('__invoke')); $callable->expects($this->once()) diff --git a/tests/Predis/Command/Hash/CommandHashStrategyTest.php b/tests/Predis/Command/Hash/CommandHashStrategyTest.php index 3d43311d..6b61e9bd 100644 --- a/tests/Predis/Command/Hash/CommandHashStrategyTest.php +++ b/tests/Predis/Command/Hash/CommandHashStrategyTest.php @@ -314,7 +314,7 @@ class CommandHashStrategyTest extends StandardTestCase ); if (isset($type)) { - $commands = array_filter($commands, function($expectedType) use($type) { + $commands = array_filter($commands, function ($expectedType) use ($type) { return $expectedType === $type; }); } diff --git a/tests/Predis/CommunicationExceptionTest.php b/tests/Predis/CommunicationExceptionTest.php index b3906040..36ae11f0 100644 --- a/tests/Predis/CommunicationExceptionTest.php +++ b/tests/Predis/CommunicationExceptionTest.php @@ -72,8 +72,7 @@ class CommunicationExceptionTest extends StandardTestCase if ($parameters === null) { $builder->disableOriginalConstructor(); - } - else if (!$parameters instanceof ConnectionParametersInterface) { + } else if (!$parameters instanceof ConnectionParametersInterface) { $parameters = new ConnectionParameters($parameters); } diff --git a/tests/Predis/Connection/ConnectionFactoryTest.php b/tests/Predis/Connection/ConnectionFactoryTest.php index a8f3620b..b03339e8 100644 --- a/tests/Predis/Connection/ConnectionFactoryTest.php +++ b/tests/Predis/Connection/ConnectionFactoryTest.php @@ -133,9 +133,11 @@ class ConnectionFactoryTest extends StandardTestCase $password = 'foobar'; $commands = array(); - $createCommand = function($id, $arguments) use($test, &$commands) { + $createCommand = function ($id, $arguments) use ($test, &$commands) { $commands[$id] = $arguments; - return $test->getMock('Predis\Command\CommandInterface'); + $command = $test->getMock('Predis\Command\CommandInterface'); + + return $command; }; $profile = $this->getMock('Predis\Profile\ServerProfileInterface'); @@ -191,7 +193,7 @@ class ConnectionFactoryTest extends StandardTestCase $parameters = new ConnectionParameters(array('scheme' => 'foobar')); - $initializer = function($parameters) use($connectionClass) { + $initializer = function ($parameters) use ($connectionClass) { return new $connectionClass($parameters); }; @@ -297,7 +299,7 @@ class ConnectionFactoryTest extends StandardTestCase $factory = $this->getMock('Predis\Connection\ConnectionFactory', array('create')); $factory->expects($this->exactly(3)) ->method('create') - ->will($this->returnCallback(function($_, $_) use($connectionClass) { + ->will($this->returnCallback(function ($_, $_) use ($connectionClass) { return new $connectionClass; })); @@ -333,7 +335,7 @@ class ConnectionFactoryTest extends StandardTestCase $factory->expects($this->exactly(2)) ->method('create') ->with($this->anything(), $profile) - ->will($this->returnCallback(function($_, $_) use($connectionClass) { + ->will($this->returnCallback(function ($_, $_) use ($connectionClass) { return new $connectionClass(); })); diff --git a/tests/Predis/Connection/MasterSlaveReplicationTest.php b/tests/Predis/Connection/MasterSlaveReplicationTest.php index c6221fb2..ca736255 100644 --- a/tests/Predis/Connection/MasterSlaveReplicationTest.php +++ b/tests/Predis/Connection/MasterSlaveReplicationTest.php @@ -493,7 +493,7 @@ class MasterSlaveReplicationTest extends StandardTestCase $replication->add($master); $replication->add($slave1); - $replication->setCommandReadOnly('exists', function($cmd) { + $replication->setCommandReadOnly('exists', function ($cmd) { list($arg1) = $cmd->getArguments(); return $arg1 === 'foo'; }); diff --git a/tests/Predis/Option/ClientClusterTest.php b/tests/Predis/Option/ClientClusterTest.php index 279bf327..407c44fc 100644 --- a/tests/Predis/Option/ClientClusterTest.php +++ b/tests/Predis/Option/ClientClusterTest.php @@ -102,7 +102,9 @@ class ClientClusterTest extends StandardTestCase { $this->setExpectedException('InvalidArgumentException'); - $value = function($options) { return new \stdClass(); }; + $value = function ($options) { + return new \stdClass(); + }; $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); diff --git a/tests/Predis/Option/ClientProfileTest.php b/tests/Predis/Option/ClientProfileTest.php index 0a6c7ae1..2b696534 100644 --- a/tests/Predis/Option/ClientProfileTest.php +++ b/tests/Predis/Option/ClientProfileTest.php @@ -199,7 +199,9 @@ class ClientProfileTest extends StandardTestCase */ public function testValidationThrowsExceptionOnInvalidObjectReturnedByCallback() { - $value = function($options) { return new \stdClass(); }; + $value = function ($options) { + return new \stdClass(); + }; $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientProfile(); diff --git a/tests/Predis/Pipeline/PipelineContextTest.php b/tests/Predis/Pipeline/PipelineContextTest.php index 7d9cde1c..8fce8390 100644 --- a/tests/Predis/Pipeline/PipelineContextTest.php +++ b/tests/Predis/Pipeline/PipelineContextTest.php @@ -178,7 +178,7 @@ class PipelineContextTest extends StandardTestCase $test = $this; $pipeline = new PipelineContext(new Client()); - $callable = function($pipe) use($test, $pipeline) { + $callable = function ($pipe) use ($test, $pipeline) { $test->assertSame($pipeline, $pipe); $pipe->flushPipeline(false); }; @@ -206,7 +206,7 @@ class PipelineContextTest extends StandardTestCase { $pipeline = new PipelineContext(new Client()); - $pipeline->execute(function($pipe) { + $pipeline->execute(function ($pipe) { $pipe->execute(); }); } @@ -225,7 +225,7 @@ class PipelineContextTest extends StandardTestCase $pipeline = new PipelineContext(new Client($connection)); - $replies = $pipeline->execute(function($pipe) { + $replies = $pipeline->execute(function ($pipe) { $pipe->echo('one'); $pipe->echo('two'); $pipe->echo('three'); @@ -250,13 +250,12 @@ class PipelineContextTest extends StandardTestCase $replies = null; try { - $replies = $pipeline->execute(function($pipe) { + $replies = $pipeline->execute(function ($pipe) { $pipe->echo('one'); throw new ClientException('TEST'); $pipe->echo('two'); }); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { $exception = $ex; } @@ -291,7 +290,7 @@ class PipelineContextTest extends StandardTestCase { $client = $this->getClient(); - $results = $client->pipeline(function($pipe) { + $results = $client->pipeline(function ($pipe) { $pipe->set('foo', 'bar'); $pipe->get('foo'); }); @@ -308,7 +307,7 @@ class PipelineContextTest extends StandardTestCase $oob = null; $client = $this->getClient(); - $results = $client->pipeline(function($pipe) use(&$oob) { + $results = $client->pipeline(function ($pipe) use (&$oob) { $pipe->set('foo', 'bar'); $oob = $pipe->getClient()->echo('oob message'); $pipe->get('foo'); @@ -327,12 +326,11 @@ class PipelineContextTest extends StandardTestCase $client = $this->getClient(); try { - $client->pipeline(function($pipe) { + $client->pipeline(function ($pipe) { $pipe->set('foo', 'bar'); throw new ClientException('TEST'); }); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { $exception = $ex; } @@ -349,15 +347,14 @@ class PipelineContextTest extends StandardTestCase $client = $this->getClient(); try { - $client->pipeline(function($pipe) { + $client->pipeline(function ($pipe) { $pipe->set('foo', 'bar'); // LPUSH on a string key fails, but won't stop // the pipeline to send the commands. $pipe->lpush('foo', 'bar'); $pipe->set('hoge', 'piyo'); }); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { $exception = $ex; } @@ -373,7 +370,7 @@ class PipelineContextTest extends StandardTestCase { $client = $this->getClient(array(), array('exceptions' => false)); - $results = $client->pipeline(function($pipe) { + $results = $client->pipeline(function ($pipe) { $pipe->set('foo', 'bar'); $pipe->lpush('foo', 'bar'); // LPUSH on a string key fails. $pipe->get('foo'); @@ -425,12 +422,13 @@ class PipelineContextTest extends StandardTestCase */ protected function getReadCallback() { - return function($command) { + return function ($command) { if (($id = $command->getId()) !== 'ECHO') { throw new \InvalidArgumentException("Expected ECHO, got {$id}"); } list($echoed) = $command->getArguments(); + return $echoed; }; } diff --git a/tests/Predis/Profile/ServerProfileTest.php b/tests/Predis/Profile/ServerProfileTest.php index bb1e3e56..82396cf4 100644 --- a/tests/Predis/Profile/ServerProfileTest.php +++ b/tests/Predis/Profile/ServerProfileTest.php @@ -263,7 +263,7 @@ class ServerProfileTest extends StandardTestCase $processor->expects($this->once()) ->method('process') ->with($this->isInstanceOf('Predis\Command\CommandInterface')) - ->will($this->returnCallback(function($cmd) use(&$argsRef) { + ->will($this->returnCallback(function ($cmd) use (&$argsRef) { $cmd->setRawArguments($argsRef = array_map('strtoupper', $cmd->getArguments())); })); diff --git a/tests/Predis/PubSub/DispatcherLoopTest.php b/tests/Predis/PubSub/DispatcherLoopTest.php index a2c9f8b1..263469b2 100644 --- a/tests/Predis/PubSub/DispatcherLoopTest.php +++ b/tests/Predis/PubSub/DispatcherLoopTest.php @@ -55,7 +55,7 @@ class DispatcherLoopTest extends StandardTestCase $this->equalTo('01:argument'), $this->equalTo('01:quit') )) - ->will($this->returnCallback(function($arg) use($dispatcher) { + ->will($this->returnCallback(function ($arg) use ($dispatcher) { if ($arg === '01:quit') { $dispatcher->stop(); } diff --git a/tests/Predis/PubSub/PubSubContextTest.php b/tests/Predis/PubSub/PubSubContextTest.php index ab397d4b..5bc36ca2 100644 --- a/tests/Predis/PubSub/PubSubContextTest.php +++ b/tests/Predis/PubSub/PubSubContextTest.php @@ -80,7 +80,7 @@ class PubSubContextTest extends StandardTestCase $client->expects($this->exactly(2)) ->method('createCommand') ->with($this->logicalOr($this->equalTo('subscribe'), $this->equalTo('psubscribe'))) - ->will($this->returnCallback(function($id, $args) use($profile) { + ->will($this->returnCallback(function ($id, $args) use ($profile) { return $profile->createCommand($id, $args); })); diff --git a/tests/Predis/Transaction/MultiExecContextTest.php b/tests/Predis/Transaction/MultiExecContextTest.php index 988737fb..c22286f1 100644 --- a/tests/Predis/Transaction/MultiExecContextTest.php +++ b/tests/Predis/Transaction/MultiExecContextTest.php @@ -75,7 +75,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback($expected, $commands); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->echo('one'); $tx->echo('two'); $tx->echo('three'); @@ -98,9 +98,10 @@ class MultiExecContextTest extends StandardTestCase $exception = null; try { - $tx->echo('foo')->execute(function($tx) { $tx->echo('bar'); }); - } - catch (\Exception $ex) { + $tx->echo('foo')->execute(function ($tx) { + $tx->echo('bar'); + }); + } catch (\Exception $ex) { $exception = $ex; } @@ -118,7 +119,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(null, $commands); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { // NOOP }); @@ -138,7 +139,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(null, $commands); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->exec(); }); @@ -156,7 +157,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(null, $commands); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->discard(); }); @@ -174,7 +175,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(null, $commands); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->set('foo', 'bar'); $tx->get('foo'); $tx->discard(); @@ -195,7 +196,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback($expected, $commands); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->echo('before DISCARD'); $tx->discard(); $tx->echo('after DISCARD'); @@ -245,7 +246,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback($expected, $txCommands, $casCommands); $tx = $this->getMockedTransaction($callback, $options); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->get('foo'); $tx->get('hoge'); }); @@ -294,7 +295,7 @@ class MultiExecContextTest extends StandardTestCase $tx = $this->getMockedTransaction($callback, $options); $test = $this; - $replies = $tx->execute(function($tx) use($test) { + $replies = $tx->execute(function ($tx) use ($test) { $tx->watch('foobar'); $reply1 = $tx->get('foo'); @@ -325,7 +326,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(array(), $txCommands, $casCommands); $tx = $this->getMockedTransaction($callback, $options); - $tx->execute(function($tx) { + $tx->execute(function ($tx) { $tx->multi(); }); @@ -344,7 +345,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(array(), $txCommands, $casCommands); $tx = $this->getMockedTransaction($callback, $options); - $tx->execute(function($tx) { + $tx->execute(function ($tx) { $bar = $tx->get('foo'); $tx->set('hoge', 'piyo'); }); @@ -383,11 +384,13 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback($expected, $txCommands, $casCommands); $tx = $this->getMockedTransaction($callback, $options); - $replies = $tx->execute(function($tx) use($sentinel, &$attempts) { + $replies = $tx->execute(function ($tx) use ($sentinel, &$attempts) { $tx->get('foo'); + if ($attempts > 0) { $attempts -= 1; $sentinel->signal(); + $tx->echo('!!ABORT!!'); } }); @@ -407,7 +410,7 @@ class MultiExecContextTest extends StandardTestCase $callback = $this->getExecuteCallback(); $tx = $this->getMockedTransaction($callback); - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->echo('!!ABORT!!'); }); } @@ -426,13 +429,13 @@ class MultiExecContextTest extends StandardTestCase $replies = null; try { - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->set('foo', 'bar'); $tx->get('foo'); + throw new \RuntimeException('TEST'); }); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // NOOP } @@ -454,13 +457,12 @@ class MultiExecContextTest extends StandardTestCase $replies = null; try { - $replies = $tx->execute(function($tx) { + $replies = $tx->execute(function ($tx) { $tx->set('foo', 'bar'); $tx->echo('ERR Invalid operation'); $tx->get('foo'); }); - } - catch (ServerException $ex) { + } catch (ServerException $ex) { $tx->discard(); } @@ -481,12 +483,11 @@ class MultiExecContextTest extends StandardTestCase $exception = null; try { - $client->multiExec(function($tx) { + $client->multiExec(function ($tx) { $tx->set('foo', 'bar'); throw new \RuntimeException("TEST"); }); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { $exception = $ex; } @@ -504,13 +505,12 @@ class MultiExecContextTest extends StandardTestCase $value = (string) rand(); try { - $client->multiExec(function($tx) use($value) { + $client->multiExec(function ($tx) use ($value) { $tx->set('foo', 'bar'); $tx->lpush('foo', 'bar'); $tx->set('foo', $value); }); - } - catch (ServerException $ex) { + } catch (ServerException $ex) { $exception = $ex; } @@ -525,7 +525,7 @@ class MultiExecContextTest extends StandardTestCase { $client = $this->getClient(array(), array('exceptions' => false)); - $replies = $client->multiExec(function($tx) { + $replies = $client->multiExec(function ($tx) { $tx->set('foo', 'bar'); $tx->lpush('foo', 'bar'); $tx->echo('foobar'); @@ -543,7 +543,7 @@ class MultiExecContextTest extends StandardTestCase { $client = $this->getClient(); - $replies = $client->multiExec(function($tx) { + $replies = $client->multiExec(function ($tx) { $tx->set('foo', 'bar'); $tx->discard(); $tx->set('hoge', 'piyo'); @@ -564,13 +564,12 @@ class MultiExecContextTest extends StandardTestCase $client2 = $this->getClient(); try { - $client1->multiExec(array('watch' => 'sentinel'), function($tx) use($client2) { + $client1->multiExec(array('watch' => 'sentinel'), function ($tx) use ($client2) { $tx->set('sentinel', 'client1'); $tx->get('sentinel'); $client2->set('sentinel', 'client2'); }); - } - catch (AbortedMultiExecException $ex) { + } catch (AbortedMultiExecException $ex) { $exception = $ex; } @@ -588,9 +587,10 @@ class MultiExecContextTest extends StandardTestCase $client->set('foo', 'bar'); $options = array('watch' => 'foo', 'cas' => true); - $replies = $client->multiExec($options, function($tx) { + $replies = $client->multiExec($options, function ($tx) { $tx->watch('foobar'); $foo = $tx->get('foo'); + $tx->multi(); $tx->set('foobar', $foo); $tx->discard(); @@ -605,15 +605,18 @@ class MultiExecContextTest extends StandardTestCase $client->set('foo', 'bar'); $options = array('watch' => 'foo', 'cas' => true, 'retry' => 1); - $replies = $client->multiExec($options, function($tx) use($client2, &$hijack) { + $replies = $client->multiExec($options, function ($tx) use ($client2, &$hijack) { $foo = $tx->get('foo'); $tx->multi(); + $tx->set('foobar', $foo); $tx->discard(); + if ($hijack) { $hijack = false; $client2->set('foo', 'hijacked!'); } + $tx->mget('foo', 'foobar'); }); @@ -670,13 +673,12 @@ class MultiExecContextTest extends StandardTestCase { $multi = $watch = $abort = false; - return function(CommandInterface $command) use(&$expected, &$commands, &$cas, &$multi, &$watch, &$abort) { + return function (CommandInterface $command) use (&$expected, &$commands, &$cas, &$multi, &$watch, &$abort) { $cmd = $command->getId(); if ($multi || $cmd === 'MULTI') { $commands[] = $command; - } - else { + } else { $cas[] = $command; } @@ -685,31 +687,38 @@ class MultiExecContextTest extends StandardTestCase if ($multi) { throw new ServerException("ERR $cmd inside MULTI is not allowed"); } + return $watch = true; case 'MULTI': if ($multi) { throw new ServerException("ERR MULTI calls can not be nested"); } + return $multi = true; case 'EXEC': if (!$multi) { throw new ServerException("ERR $cmd without MULTI"); } + $watch = $multi = false; + if ($abort) { $commands = $cas = array(); $abort = false; return null; } + return $expected; case 'DISCARD': if (!$multi) { throw new ServerException("ERR $cmd without MULTI"); } + $watch = $multi = false; + return true; case 'ECHO': @@ -717,9 +726,11 @@ class MultiExecContextTest extends StandardTestCase if (strpos($trigger, 'ERR ') === 0) { throw new ServerException($trigger); } + if ($trigger === '!!ABORT!!' && $multi) { $abort = true; } + return new ResponseQueued(); case 'UNWATCH':