diff --git a/README.markdown b/README.markdown index c45ea07d..4bedf96a 100644 --- a/README.markdown +++ b/README.markdown @@ -109,7 +109,8 @@ classes. This can be obtained by subclassing the `Predis\Network\IConnectionSing ``` php true, ); -function getPharFilename($options) { +function getPharFilename($options) +{ $filename = $options['name']; + // NOTE: do not consider "append_version" with Phar compression do to a bug in // Phar::compress() when renaming phar archives containing dots in their name. if ($options['append_version'] && $options['compression'] === Phar::NONE) { $versionFile = @fopen(__DIR__ . '/../VERSION', 'r'); + if ($versionFile === false) { throw new Exception("Could not locate the VERSION file."); } + $version = trim(fgets($versionFile)); fclose($versionFile); $filename .= "_$version"; } + return "$filename.phar"; } -function getPharStub($options) { +function getPharStub($options) +{ return << 'source:', 'o:' => 'output:', @@ -23,6 +25,7 @@ class CommandLine { ); $getops = getopt(implode(array_keys($parameters)), $parameters); + $options = array( 'source' => __DIR__ . "/../lib/", 'output' => PredisFile::NS_ROOT . '.php', @@ -35,14 +38,17 @@ class CommandLine { case 'source': $options['source'] = $value; break; + case 'o': case 'output': $options['output'] = $value; break; + case 'E': case 'exclude-classes': $options['exclude'] = @file($value, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: $value; break; + case 'e': case 'exclude': $options['exclude'] = is_array($value) ? $value : array($value); @@ -54,120 +60,151 @@ class CommandLine { } } -class PredisFile { +class PredisFile +{ const NS_ROOT = 'Predis'; + private $_namespaces; - public function __construct() { + public function __construct() + { $this->_namespaces = array(); } - public static function from($libraryPath, Array $exclude = array()) { + public static function from($libraryPath, Array $exclude = array()) + { $nsroot = self::NS_ROOT; $predisFile = new PredisFile(); $libIterator = new RecursiveDirectoryIterator("$libraryPath$nsroot"); - foreach (new RecursiveIteratorIterator($libIterator) as $classFile) { + foreach (new RecursiveIteratorIterator($libIterator) as $classFile) + { if (!$classFile->isFile()) { continue; } $namespace = strtr(str_replace($libraryPath, '', $classFile->getPath()), '/', '\\'); + if (in_array(sprintf('%s\\%s', $namespace, $classFile->getBasename('.php')), $exclude)) { continue; } $phpNamespace = $predisFile->getNamespace($namespace); + if ($phpNamespace === false) { $phpNamespace = new PhpNamespace($namespace); $predisFile->addNamespace($phpNamespace); } + $phpClass = new PhpClass($phpNamespace, $classFile); } + return $predisFile; } - public function addNamespace(PhpNamespace $namespace) { + public function addNamespace(PhpNamespace $namespace) + { if (isset($this->_namespaces[(string)$namespace])) { throw new InvalidArgumentException("Duplicated namespace"); } $this->_namespaces[(string)$namespace] = $namespace; } - public function getNamespaces() { + public function getNamespaces() + { return $this->_namespaces; } - public function getNamespace($namespace) { + public function getNamespace($namespace) + { if (!isset($this->_namespaces[$namespace])) { return false; } + return $this->_namespaces[$namespace]; } - public function getClassByFQN($classFqn) { + public function getClassByFQN($classFqn) + { if (($nsLastPos = strrpos($classFqn, '\\')) !== false) { $namespace = $this->getNamespace(substr($classFqn, 0, $nsLastPos)); if ($namespace === false) { return null; } $className = substr($classFqn, $nsLastPos + 1); + return $namespace->getClass($className); } + return null; } - private function calculateDependencyScores(&$classes, $fqn) { + private function calculateDependencyScores(&$classes, $fqn) + { if (!isset($classes[$fqn])) { $classes[$fqn] = 0; } + $classes[$fqn] += 1; + if (($phpClass = $this->getClassByFQN($fqn)) === null) { - throw new RuntimeException("Cannot found the class $fqn which is required by other subclasses. Are you missing a file?"); + throw new RuntimeException( + "Cannot found the class $fqn which is required by other subclasses. Are you missing a file?" + ); } + foreach ($phpClass->getDependencies() as $fqn) { $this->calculateDependencyScores($classes, $fqn); } } - private function getDependencyScores() { + private function getDependencyScores() + { $classes = array(); + foreach ($this->getNamespaces() as $phpNamespace) { foreach ($phpNamespace->getClasses() as $phpClass) { $this->calculateDependencyScores($classes, $phpClass->getFQN()); } } + return $classes; } - private function getOrderedNamespaces($dependencyScores) { + private function getOrderedNamespaces($dependencyScores) + { $namespaces = array_fill_keys(array_unique( array_map( function($fqn) { return PhpNamespace::extractName($fqn); }, array_keys($dependencyScores) ) ), 0); + foreach ($dependencyScores as $classFqn => $score) { $namespaces[PhpNamespace::extractName($classFqn)] += $score; } + arsort($namespaces); + return array_keys($namespaces); } - private function getOrderedClasses(PhpNamespace $phpNamespace, $classes) { - $nsClassesFQNs = array_map( - function($cl) { return $cl->getFQN(); }, - $phpNamespace->getClasses() - ); + private function getOrderedClasses(PhpNamespace $phpNamespace, $classes) + { + $nsClassesFQNs = array_map(function($cl) { return $cl->getFQN(); }, $phpNamespace->getClasses()); $nsOrderedClasses = array(); + foreach ($nsClassesFQNs as $nsClassFQN) { $nsOrderedClasses[$nsClassFQN] = $classes[$nsClassFQN]; } + arsort($nsOrderedClasses); + return array_keys($nsOrderedClasses); } - public function getPhpCode() { + public function getPhpCode() + { $buffer = array("getDependencyScores(); $namespaces = $this->getOrderedNamespaces($classes); @@ -196,10 +233,12 @@ class PredisFile { $buffer[] = "/* " . str_repeat("-", 75) . " */"; $buffer[] = "\n\n"; } + return implode($buffer); } - public function saveTo($outputFile) { + public function saveTo($outputFile) + { // TODO: add more sanity checks if ($outputFile === null || $outputFile === '') { throw new InvalidArgumentException('You must specify a valid output file'); @@ -208,127 +247,167 @@ class PredisFile { } } -class PhpNamespace implements IteratorAggregate { - private $_namespace, $_classes; +class PhpNamespace implements IteratorAggregate +{ + private $_namespace; + private $_classes; - public function __construct($namespace) { + public function __construct($namespace) + { $this->_namespace = $namespace; $this->_classes = array(); $this->_useDirectives = new PhpUseDirectives($this); } - public static function extractName($fqn) { + public static function extractName($fqn) + { $nsSepLast = strrpos($fqn, '\\'); if ($nsSepLast === false) { return $fqn; } $ns = substr($fqn, 0, $nsSepLast); + return $ns !== '' ? $ns : null; } - public function addClass(PhpClass $class) { + public function addClass(PhpClass $class) + { $this->_classes[$class->getName()] = $class; } - public function getClass($className) { + public function getClass($className) + { if (isset($this->_classes[$className])) { return $this->_classes[$className]; } } - public function getClasses() { + public function getClasses() + { return array_values($this->_classes); } - public function getIterator() { + public function getIterator() + { return new \ArrayIterator($this->getClasses()); } - public function getUseDirectives() { + public function getUseDirectives() + { return $this->_useDirectives; } - public function getPhpCode() { + public function getPhpCode() + { return "namespace $this->_namespace;\n"; } - public function __toString() { + public function __toString() + { return $this->_namespace; } } -class PhpUseDirectives implements Countable, IteratorAggregate { - private $_use, $_aliases, $_namespace; +class PhpUseDirectives implements Countable, IteratorAggregate +{ + private $_use; + private $_aliases; + private $_namespace; - public function __construct(PhpNamespace $namespace) { + public function __construct(PhpNamespace $namespace) + { $this->_use = array(); $this->_aliases = array(); $this->_namespace = $namespace; } - public function add($use, $as = null) { - if (!in_array($use, $this->_use)) { - $this->_use[] = $use; - $this->_aliases[$as ?: PhpClass::extractName($use)] = $use; + public function add($use, $as = null) + { + if (in_array($use, $this->_use)) { + return; } + + $this->_use[] = $use; + $this->_aliases[$as ?: PhpClass::extractName($use)] = $use; } - public function getList() { + public function getList() + { return $this->_use; } - public function getIterator() { + public function getIterator() + { return new \ArrayIterator($this->getList()); } - public function getPhpCode() { + public function getPhpCode() + { $reducer = function($str, $use) { return $str .= "use $use;\n"; }; + return array_reduce($this->getList(), $reducer, ''); } - public function getNamespace() { + public function getNamespace() + { return $this->_namespace; } - public function getFQN($className) { + public function getFQN($className) + { if (($nsSepFirst = strpos($className, '\\')) === false) { if (isset($this->_aliases[$className])) { return $this->_aliases[$className]; } + return (string)$this->getNamespace() . "\\$className"; } + if ($nsSepFirst != 0) { throw new InvalidArgumentException("Partially qualified names are not supported"); } + return $className; } - public function count() { + public function count() + { return count($this->_use); } } -class PhpClass { - private $_namespace, $_file, $_body, $_implements, $_extends, $_name; +class PhpClass +{ + private $_namespace; + private $_file; + private $_body; + private $_implements; + private $_extends; + private $_name; - public function __construct(PhpNamespace $namespace, SplFileInfo $classFile) { + public function __construct(PhpNamespace $namespace, SplFileInfo $classFile) + { $this->_namespace = $namespace; $this->_file = $classFile; $this->_implements = array(); $this->_extends = array(); + $this->extractData(); $namespace->addClass($this); } - public static function extractName($fqn) { + public static function extractName($fqn) + { $nsSepLast = strrpos($fqn, '\\'); if ($nsSepLast === false) { return $fqn; } + return substr($fqn, $nsSepLast + 1); } - private function extractData() { + private function extractData() + { $useDirectives = $this->getNamespace()->getUseDirectives(); $useExtractor = function($m) use($useDirectives) { @@ -347,15 +426,18 @@ class PhpClass { $this->extractHierarchy(); } - private function extractHierarchy() { + private function extractHierarchy() + { $implements = array(); $extends = array(); $extractor = function($iterator, $callback) { $className = ''; $iterator->seek($iterator->key() + 1); + while ($iterator->valid()) { $token = $iterator->current(); + if (is_string($token)) { if (preg_match('/\s?,\s?/', $token)) { $callback(trim($className)); @@ -366,26 +448,30 @@ class PhpClass { return; } } + switch ($token[0]) { case T_NS_SEPARATOR: $className .= '\\'; break; + case T_STRING: $className .= $token[1]; break; + case T_IMPLEMENTS: case T_EXTENDS: $callback(trim($className)); $iterator->seek($iterator->key() - 1); return; } + $iterator->next(); } }; $tokens = token_get_all("getPhpCode())); - $iterator = new ArrayIterator($tokens); + while ($iterator->valid()) { $token = $iterator->current(); if (is_string($token)) { @@ -400,17 +486,20 @@ class PhpClass { $tk = $iterator->current(); $this->_name = $tk[1]; break; + case T_IMPLEMENTS: $extractor($iterator, function($fqn) use (&$implements) { $implements[] = $fqn; }); break; + case T_EXTENDS: $extractor($iterator, function($fqn) use (&$extends) { $extends[] = $fqn; }); break; } + $iterator->next(); } @@ -418,63 +507,71 @@ class PhpClass { $this->_extends = $this->guessFQN($extends); } - public function guessFQN($classes) { + public function guessFQN($classes) + { $useDirectives = $this->getNamespace()->getUseDirectives(); return array_map(array($useDirectives, 'getFQN'), $classes); } - public function getImplementedInterfaces($all = false) { + public function getImplementedInterfaces($all = false) + { if ($all) { return $this->_implements; } - else { - return array_filter( - $this->_implements, - function ($cn) { return strpos($cn, 'Predis\\') === 0; } - ); - } + + return array_filter( + $this->_implements, + function ($cn) { return strpos($cn, 'Predis\\') === 0; } + ); } - public function getExtendedClasses($all = false) { + public function getExtendedClasses($all = false) + { if ($all) { return $this->_extemds; } - else { - return array_filter( - $this->_extends, - function ($cn) { return strpos($cn, 'Predis\\') === 0; } - ); - } + + return array_filter( + $this->_extends, + function ($cn) { return strpos($cn, 'Predis\\') === 0; } + ); } - public function getDependencies($all = false) { + public function getDependencies($all = false) + { return array_merge( $this->getImplementedInterfaces($all), $this->getExtendedClasses($all) ); } - public function getNamespace() { + public function getNamespace() + { return $this->_namespace; } - public function getFile() { + public function getFile() + { return $this->_file; } - public function getName() { + public function getName() + { return $this->_name; } - public function getFQN() { + public function getFQN() + { return (string)$this->getNamespace() . '\\' . $this->_name; } - public function getPhpCode() { + public function getPhpCode() + { return $this->_body; } - public function __toString() { + public function __toString() + { return "class " . $this->getName() . '{ ... }'; } } diff --git a/examples/CustomDistributionStrategy.php b/examples/CustomDistributionStrategy.php index 9af1ae56..8edd24a5 100644 --- a/examples/CustomDistributionStrategy.php +++ b/examples/CustomDistributionStrategy.php @@ -9,35 +9,44 @@ require 'SharedConfigurations.php'; use Predis\Distribution\IDistributionStrategy; use Predis\Network\PredisCluster; -class NaiveDistributionStrategy implements IDistributionStrategy { - private $_nodes, $_nodesCount; +class NaiveDistributionStrategy implements IDistributionStrategy +{ + private $_nodes; + private $_nodesCount; - public function __constructor() { + public function __constructor() + { $this->_nodes = array(); $this->_nodesCount = 0; } - public function add($node, $weight = null) { + public function add($node, $weight = null) + { $this->_nodes[] = $node; $this->_nodesCount++; } - public function remove($node) { + public function remove($node) + { $this->_nodes = array_filter($this->_nodes, function($n) use($node) { return $n !== $node; }); + $this->_nodesCount = count($this->_nodes); } - public function get($key) { + public function get($key) + { $count = $this->_nodesCount; if ($count === 0) { throw new RuntimeException('No connections'); } + return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0]; } - public function generateKey($value) { + public function generateKey($value) + { return crc32($value); } } diff --git a/examples/DispatcherLoop.php b/examples/DispatcherLoop.php index 11b4a31d..512817d8 100644 --- a/examples/DispatcherLoop.php +++ b/examples/DispatcherLoop.php @@ -22,22 +22,27 @@ $client = new Predis\Client($single_server + array('read_write_timeout' => 0)); $dispatcher = new Predis\DispatcherLoop($client); // Demonstrate how to use a callable class as a callback for Predis\DispatcherLoop. -class EventsListener implements Countable { +class EventsListener implements Countable +{ private $_events; - public function __construct() { + public function __construct() + { $this->_events = array(); } - public function count() { + public function count() + { return count($this->_events); } - public function getEvents() { + public function getEvents() + { return $this->_events; } - public function __invoke($payload) { + public function __invoke($payload) + { $this->_events[] = $payload; } } diff --git a/examples/MultiExecTransactionsWithCAS.php b/examples/MultiExecTransactionsWithCAS.php index 0a28eaf6..38aad178 100644 --- a/examples/MultiExecTransactionsWithCAS.php +++ b/examples/MultiExecTransactionsWithCAS.php @@ -16,26 +16,29 @@ ZADD zset 2 b ZADD zset 3 c */ -function zpop($client, $zsetKey) { +function zpop($client, $key) +{ $element = null; + $options = array( - 'cas' => true, // Initialize with support for CAS operations - 'watch' => $zsetKey, // Key that needs to be WATCHed to detect changes - 'retry' => 3, // Number of retries on aborted transactions, after - // which the client bails out with an exception. + 'cas' => true, // Initialize with support for CAS operations + 'watch' => $key, // Key that needs to be WATCHed to detect changes + 'retry' => 3, // Number of retries on aborted transactions, after + // which the client bails out with an exception. ); - $txReply = $client->multiExec($options, function($tx) - use ($zsetKey, &$element) { - @list($element) = $tx->zrange($zsetKey, 0, 0); + $txReply = $client->multiExec($options, function($tx) use ($key, &$element) { + @list($element) = $tx->zrange($key, 0, 0); + if (isset($element)) { - $tx->multi(); // With CAS, MULTI *must* be explicitly invoked. - $tx->zrem($zsetKey, $element); + $tx->multi(); // With CAS, MULTI *must* be explicitly invoked. + $tx->zrem($key, $element); } }); return $element; } -$redis = new Predis\Client($single_server, 'dev'); +$redis = new Predis\Client($single_server); $zpopped = zpop($redis, 'zset'); + echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "\n"; diff --git a/examples/PubSubContext.php b/examples/PubSubContext.php index 1eaff005..2b18ca50 100644 --- a/examples/PubSubContext.php +++ b/examples/PubSubContext.php @@ -23,6 +23,7 @@ foreach ($pubsub as $message) { case 'subscribe': echo "Subscribed to {$message->channel}\n"; break; + case 'message': if ($message->channel == 'control_channel') { if ($message->payload == 'quit_loop') { diff --git a/examples/ServerSideScripting.php b/examples/ServerSideScripting.php index df1599c5..ec78ef60 100644 --- a/examples/ServerSideScripting.php +++ b/examples/ServerSideScripting.php @@ -9,12 +9,15 @@ require 'SharedConfigurations.php'; use Predis\Commands\ScriptedCommand; -class IncrementExistingKey extends ScriptedCommand { - protected function keysCount() { +class IncrementExistingKey extends ScriptedCommand +{ + protected function keysCount() + { return 1; } - public function getScript() { + public function getScript() + { return <<getProfile()->defineCommand('increx', 'IncrementExistingKey'); $client->set('foo', 10); + var_dump($client->increx('foo')); // int(11) var_dump($client->increx('bar')); // NULL diff --git a/examples/SimpleDebuggableConnection.php b/examples/SimpleDebuggableConnection.php index 98670b10..b5d47f00 100644 --- a/examples/SimpleDebuggableConnection.php +++ b/examples/SimpleDebuggableConnection.php @@ -6,37 +6,48 @@ use Predis\ConnectionParameters; use Predis\Commands\ICommand; use Predis\Network\StreamConnection; -class SimpleDebuggableConnection extends StreamConnection { - private $_debugBuffer = array(); +class SimpleDebuggableConnection extends StreamConnection +{ private $_tstart = 0; + private $_debugBuffer = array(); - public function connect() { + public function connect() + { $this->_tstart = microtime(true); + parent::connect(); } - private function storeDebug(ICommand $command, $direction) { + private function storeDebug(ICommand $command, $direction) + { $firtsArg = $command->getArgument(0); $timestamp = round(microtime(true) - $this->_tstart, 4); + $debug = $command->getId(); $debug .= isset($firtsArg) ? " $firtsArg " : ' '; $debug .= "$direction $this"; $debug .= " [{$timestamp}s]"; + $this->_debugBuffer[] = $debug; } - public function writeCommand(ICommand $command) { + public function writeCommand(ICommand $command) + { parent::writeCommand($command); + $this->storeDebug($command, '->'); } - public function readResponse(ICommand $command) { + public function readResponse(ICommand $command) + { $reply = parent::readResponse($command); $this->storeDebug($command, '<-'); + return $reply; } - public function getDebugBuffer() { + public function getDebugBuffer() + { return $this->_debugBuffer; } } diff --git a/lib/Predis/Autoloader.php b/lib/Predis/Autoloader.php index bd9829fb..96cdc43a 100644 --- a/lib/Predis/Autoloader.php +++ b/lib/Predis/Autoloader.php @@ -2,20 +2,24 @@ namespace Predis; -class Autoloader { +class Autoloader +{ private $base_directory; private $prefix; - public function __construct($base_directory=NULL) { + public function __construct($base_directory = null) + { $this->base_directory = $base_directory ?: dirname(__FILE__); $this->prefix = __NAMESPACE__ . '\\'; } - public static function register() { + public static function register() + { spl_autoload_register(array(new self, 'autoload')); } - public function autoload($class_name) { + public function autoload($class_name) + { if (0 !== strpos($class_name, $this->prefix)) { return; } diff --git a/lib/Predis/Client.php b/lib/Predis/Client.php index 35443ac4..717d444f 100644 --- a/lib/Predis/Client.php +++ b/lib/Predis/Client.php @@ -15,142 +15,169 @@ class Client { private $_options; private $_profile; - private $_connectionFactory; private $_connection; + private $_connectionFactory; - public function __construct($parameters = null, $options = null) { + public function __construct($parameters = null, $options = null) + { $options = $this->filterOptions($options); $profile = $options->profile; + if (isset($options->prefix)) { $profile->setProcessor($options->prefix); } + $this->_options = $options; $this->_profile = $profile; $this->_connectionFactory = $options->connections; $this->_connection = $this->initializeConnection($parameters); } - private function filterOptions($options) { + private function filterOptions($options) + { if ($options === null) { return new ClientOptions(); } + if (is_array($options)) { return new ClientOptions($options); } + if ($options instanceof ClientOptions) { return $options; } + if ($options instanceof IServerProfile) { return new ClientOptions(array('profile' => $options)); } + if (is_string($options)) { return new ClientOptions(array('profile' => ServerProfile::get($options))); } + throw new \InvalidArgumentException("Invalid type for client options"); } - private function initializeConnection($parameters) { + private function initializeConnection($parameters) + { if ($parameters === null) { return $this->createConnection(new ConnectionParameters()); } + if (is_array($parameters)) { if (isset($parameters[0])) { $cluster = $this->_options->cluster; - foreach ($parameters as $single) { - $cluster->add($single instanceof IConnectionSingle - ? $single : $this->createConnection($single) - ); + foreach ($parameters as $node) { + $connection = $node instanceof IConnectionSingle ? $node : $this->createConnection($node); + $cluster->add($connection); } return $cluster; } return $this->createConnection($parameters); } + if ($parameters instanceof IConnection) { return $parameters; } + return $this->createConnection($parameters); } - protected function createConnection($parameters) { + protected function createConnection($parameters) + { $connection = $this->_connectionFactory->create($parameters); $parameters = $connection->getParameters(); + if (isset($parameters->password)) { - $connection->pushInitCommand( - $this->createCommand('auth', array($parameters->password)) - ); + $command = $this->createCommand('auth', array($parameters->password)); + $connection->pushInitCommand($command); } + if (isset($parameters->database)) { - $connection->pushInitCommand( - $this->createCommand('select', array($parameters->database)) - ); + $command = $this->createCommand('select', array($parameters->database)); + $connection->pushInitCommand($command); } + return $connection; } - public function getProfile() { + public function getProfile() + { return $this->_profile; } - public function getOptions() { + public function getOptions() + { return $this->_options; } - public function getConnectionFactory() { + public function getConnectionFactory() + { return $this->_connectionFactory; } - public function getClientFor($connectionAlias) { + public function getClientFor($connectionAlias) + { if (($connection = $this->getConnection($connectionAlias)) === null) { - throw new \InvalidArgumentException( - "Invalid connection alias: '$connectionAlias'" - ); + throw new \InvalidArgumentException("Invalid connection alias: '$connectionAlias'"); } + return new Client($connection, $this->_options); } - public function connect() { + public function connect() + { $this->_connection->connect(); } - public function disconnect() { + public function disconnect() + { $this->_connection->disconnect(); } - public function quit() { + public function quit() + { $this->disconnect(); } - public function isConnected() { + public function isConnected() + { return $this->_connection->isConnected(); } - public function getConnection($id = null) { + public function getConnection($id = null) + { if (isset($id)) { if (!Helpers::isCluster($this->_connection)) { throw new ClientException( - 'Retrieving connections by alias is supported '. - 'only with clustered connections' + 'Retrieving connections by alias is supported only with clustered connections' ); } + return $this->_connection->getConnectionById($id); } + return $this->_connection; } - public function __call($method, $arguments) { + public function __call($method, $arguments) + { $command = $this->_profile->createCommand($method, $arguments); return $this->_connection->executeCommand($command); } - public function createCommand($method, $arguments = array()) { + public function createCommand($method, $arguments = array()) + { return $this->_profile->createCommand($method, $arguments); } - public function executeCommand(ICommand $command) { + public function executeCommand(ICommand $command) + { return $this->_connection->executeCommand($command); } - public function executeCommandOnShards(ICommand $command) { + public function executeCommandOnShards(ICommand $command) + { if (Helpers::isCluster($this->_connection)) { $replies = array(); foreach ($this->_connection as $connection) { @@ -158,58 +185,69 @@ class Client { } return $replies; } + return array($this->_connection->executeCommand($command)); } - private function sharedInitializer($argv, $initializer) { + private function sharedInitializer($argv, $initializer) + { switch (count($argv)) { case 0: return $this->$initializer(); + case 1: list($arg0) = $argv; - return is_array($arg0) - ? $this->$initializer($arg0) - : $this->$initializer(null, $arg0); + return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0); + case 2: list($arg0, $arg1) = $argv; return $this->$initializer($arg0, $arg1); + default: return $this->$initializer($this, $argv); } } - public function pipeline(/* arguments */) { + public function pipeline(/* arguments */) + { return $this->sharedInitializer(func_get_args(), 'initPipeline'); } - protected function initPipeline(Array $options = null, $pipelineBlock = null) { - return $this->pipelineExecute( - new PipelineContext($this, $options), $pipelineBlock - ); + protected function initPipeline(Array $options = null, $pipelineBlock = null) + { + $pipeline = new PipelineContext($this, $options); + return $this->pipelineExecute($pipeline, $pipelineBlock); } - private function pipelineExecute(PipelineContext $pipeline, $block) { + private function pipelineExecute(PipelineContext $pipeline, $block) + { return $block !== null ? $pipeline->execute($block) : $pipeline; } - public function multiExec(/* arguments */) { + public function multiExec(/* arguments */) + { return $this->sharedInitializer(func_get_args(), 'initMultiExec'); } - protected function initMultiExec(Array $options = null, $block = null) { + protected function initMultiExec(Array $options = null, $block = null) + { $transaction = new MultiExecContext($this, $options ?: array()); return isset($block) ? $transaction->execute($block) : $transaction; } - public function pubSub(/* arguments */) { + public function pubSub(/* arguments */) + { return $this->sharedInitializer(func_get_args(), 'initPubSub'); } - protected function initPubSub(Array $options = null, $block = null) { + protected function initPubSub(Array $options = null, $block = null) + { $pubsub = new PubSubContext($this, $options); + if (!isset($block)) { return $pubsub; } + foreach ($pubsub as $message) { if ($block($pubsub, $message) === false) { $pubsub->closeContext(); @@ -217,7 +255,8 @@ class Client { } } - public function monitor() { + public function monitor() + { return new MonitorContext($this); } } diff --git a/lib/Predis/ClientException.php b/lib/Predis/ClientException.php index 06dcfde1..e2b5508e 100644 --- a/lib/Predis/ClientException.php +++ b/lib/Predis/ClientException.php @@ -2,5 +2,6 @@ namespace Predis; -class ClientException extends PredisException { +class ClientException extends PredisException +{ } diff --git a/lib/Predis/ClientOptions.php b/lib/Predis/ClientOptions.php index be616333..3bc97c4d 100644 --- a/lib/Predis/ClientOptions.php +++ b/lib/Predis/ClientOptions.php @@ -8,43 +8,53 @@ use Predis\Options\ClientProfile; use Predis\Options\ClientCluster; use Predis\Options\ClientConnectionFactory; -class ClientOptions { +class ClientOptions +{ private static $_sharedOptions; - private $_options = array(); private $_handlers; private $_defined; - public function __construct(Array $options = array()) { + private $_options = array(); + + public function __construct(Array $options = array()) + { $this->_handlers = $this->initialize($options); $this->_defined = array_keys($options); } - private static function getSharedOptions() { + private static function getSharedOptions() + { if (isset(self::$_sharedOptions)) { return self::$_sharedOptions; } + self::$_sharedOptions = array( 'profile' => new ClientProfile(), 'connections' => new ClientConnectionFactory(), 'cluster' => new ClientCluster(), 'prefix' => new ClientPrefix(), ); + return self::$_sharedOptions; } - public static function define($option, IOption $handler) { + public static function define($option, IOption $handler) + { self::getSharedOptions(); self::$_sharedOptions[$option] = $handler; } - public static function undefine($option) { + public static function undefine($option) + { self::getSharedOptions(); unset(self::$_sharedOptions[$option]); } - private function initialize($options) { + private function initialize($options) + { $handlers = self::getSharedOptions(); + foreach ($options as $option => $value) { if (isset($handlers[$option])) { $handler = $handlers[$option]; @@ -53,26 +63,26 @@ class ClientOptions { }; } } + return $handlers; } - public function __isset($option) { + public function __isset($option) + { return in_array($option, $this->_defined); } - public function __get($option) { + public function __get($option) + { if (isset($this->_options[$option])) { return $this->_options[$option]; } + if (isset($this->_handlers[$option])) { $handler = $this->_handlers[$option]; - if ($handler instanceof IOption) { - $value = $handler->getDefault(); - } - else { - $value = $handler(); - } + $value = $handler instanceof IOption ? $handler->getDefault() : $handler(); $this->_options[$option] = $value; + return $value; } } diff --git a/lib/Predis/Commands/Command.php b/lib/Predis/Commands/Command.php index 2b57e508..60b4ea89 100644 --- a/lib/Predis/Commands/Command.php +++ b/lib/Predis/Commands/Command.php @@ -5,40 +5,48 @@ namespace Predis\Commands; use Predis\Helpers; use Predis\Distribution\INodeKeyGenerator; -abstract class Command implements ICommand { +abstract class Command implements ICommand +{ private $_hash; private $_arguments = array(); - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return $arguments; } - public function setArguments(Array $arguments) { + public function setArguments(Array $arguments) + { $this->_arguments = $this->filterArguments($arguments); unset($this->_hash); } - public function setRawArguments(Array $arguments) { + public function setRawArguments(Array $arguments) + { $this->_arguments = $arguments; unset($this->_hash); } - public function getArguments() { + public function getArguments() + { return $this->_arguments; } - public function getArgument($index = 0) { + public function getArgument($index = 0) + { if (isset($this->_arguments[$index]) === true) { return $this->_arguments[$index]; } } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { $arguments[0] = "$prefix{$arguments[0]}"; return $arguments; } - public function prefixKeys($prefix) { + public function prefixKeys($prefix) + { $arguments = $this->onPrefixKeys($this->_arguments, $prefix); if (isset($arguments)) { $this->_arguments = $arguments; @@ -46,15 +54,19 @@ abstract class Command implements ICommand { } } - protected function canBeHashed() { + protected function canBeHashed() + { return isset($this->_arguments[0]); } - protected function checkSameHashForKeys(Array $keys) { + protected function checkSameHashForKeys(Array $keys) + { if (($count = count($keys)) === 0) { return false; } + $currentKey = Helpers::getKeyHashablePart($keys[0]); + for ($i = 1; $i < $count; $i++) { $nextKey = Helpers::getKeyHashablePart($keys[$i]); if ($currentKey !== $nextKey) { @@ -62,34 +74,43 @@ abstract class Command implements ICommand { } $currentKey = $nextKey; } + return true; } - public function getHash(INodeKeyGenerator $distributor) { + public function getHash(INodeKeyGenerator $distributor) + { if (isset($this->_hash)) { return $this->_hash; } + if ($this->canBeHashed()) { $key = Helpers::getKeyHashablePart($this->_arguments[0]); $this->_hash = $distributor->generateKey($key); + return $this->_hash; } + return null; } - public function parseResponse($data) { + public function parseResponse($data) + { return $data; } - protected function toStringArgumentReducer($accumulator, $argument) { + protected function toStringArgumentReducer($accumulator, $argument) + { if (strlen($argument) > 32) { $argument = substr($argument, 0, 32) . '[...]'; } $accumulator .= " $argument"; + return $accumulator; } - public function __toString() { + public function __toString() + { return array_reduce( $this->getArguments(), array($this, 'toStringArgumentReducer'), diff --git a/lib/Predis/Commands/ConnectionAuth.php b/lib/Predis/Commands/ConnectionAuth.php index d2fd0dcb..dd0ae0d8 100644 --- a/lib/Predis/Commands/ConnectionAuth.php +++ b/lib/Predis/Commands/ConnectionAuth.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ConnectionAuth extends Command { - public function getId() { +class ConnectionAuth extends Command +{ + public function getId() + { return 'AUTH'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ConnectionEcho.php b/lib/Predis/Commands/ConnectionEcho.php index 49cc920b..727d5fb3 100644 --- a/lib/Predis/Commands/ConnectionEcho.php +++ b/lib/Predis/Commands/ConnectionEcho.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ConnectionEcho extends Command { - public function getId() { +class ConnectionEcho extends Command +{ + public function getId() + { return 'ECHO'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ConnectionPing.php b/lib/Predis/Commands/ConnectionPing.php index 28399dc1..994861ea 100644 --- a/lib/Predis/Commands/ConnectionPing.php +++ b/lib/Predis/Commands/ConnectionPing.php @@ -2,20 +2,25 @@ namespace Predis\Commands; -class ConnectionPing extends Command { - public function getId() { +class ConnectionPing extends Command +{ + public function getId() + { return 'PING'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return $data === 'PONG' ? true : false; } } diff --git a/lib/Predis/Commands/ConnectionQuit.php b/lib/Predis/Commands/ConnectionQuit.php index e3ef0e96..0f4f19ac 100644 --- a/lib/Predis/Commands/ConnectionQuit.php +++ b/lib/Predis/Commands/ConnectionQuit.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ConnectionQuit extends Command { - public function getId() { +class ConnectionQuit extends Command +{ + public function getId() + { return 'QUIT'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ConnectionSelect.php b/lib/Predis/Commands/ConnectionSelect.php index 1caf143c..8d2a180d 100644 --- a/lib/Predis/Commands/ConnectionSelect.php +++ b/lib/Predis/Commands/ConnectionSelect.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ConnectionSelect extends Command { - public function getId() { +class ConnectionSelect extends Command +{ + public function getId() + { return 'SELECT'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/HashDelete.php b/lib/Predis/Commands/HashDelete.php index 9e8b6356..a6e7ddce 100644 --- a/lib/Predis/Commands/HashDelete.php +++ b/lib/Predis/Commands/HashDelete.php @@ -4,16 +4,20 @@ namespace Predis\Commands; use Predis\Helpers; -class HashDelete extends Command { - public function getId() { +class HashDelete extends Command +{ + public function getId() + { return 'HDEL'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/HashExists.php b/lib/Predis/Commands/HashExists.php index 5f834d7c..8a169461 100644 --- a/lib/Predis/Commands/HashExists.php +++ b/lib/Predis/Commands/HashExists.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class HashExists extends Command { - public function getId() { +class HashExists extends Command +{ + public function getId() + { return 'HEXISTS'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/HashGet.php b/lib/Predis/Commands/HashGet.php index 7b2bb7ca..16c075d9 100644 --- a/lib/Predis/Commands/HashGet.php +++ b/lib/Predis/Commands/HashGet.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class HashGet extends Command { - public function getId() { +class HashGet extends Command +{ + public function getId() + { return 'HGET'; } } diff --git a/lib/Predis/Commands/HashGetAll.php b/lib/Predis/Commands/HashGetAll.php index 45992a0d..4fdd6ba0 100644 --- a/lib/Predis/Commands/HashGetAll.php +++ b/lib/Predis/Commands/HashGetAll.php @@ -4,19 +4,24 @@ namespace Predis\Commands; use Predis\Iterators\MultiBulkResponseTuple; -class HashGetAll extends Command { - public function getId() { +class HashGetAll extends Command +{ + public function getId() + { return 'HGETALL'; } - public function parseResponse($data) { + public function parseResponse($data) + { if ($data instanceof \Iterator) { return new MultiBulkResponseTuple($data); } + $result = array(); for ($i = 0; $i < count($data); $i++) { $result[$data[$i]] = $data[++$i]; } + return $result; } } diff --git a/lib/Predis/Commands/HashGetMultiple.php b/lib/Predis/Commands/HashGetMultiple.php index 567e3b1a..9b736d8a 100644 --- a/lib/Predis/Commands/HashGetMultiple.php +++ b/lib/Predis/Commands/HashGetMultiple.php @@ -4,12 +4,15 @@ namespace Predis\Commands; use Predis\Helpers; -class HashGetMultiple extends Command { - public function getId() { +class HashGetMultiple extends Command +{ + public function getId() + { return 'HMGET'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } } diff --git a/lib/Predis/Commands/HashIncrementBy.php b/lib/Predis/Commands/HashIncrementBy.php index 7f8570c1..eeb91576 100644 --- a/lib/Predis/Commands/HashIncrementBy.php +++ b/lib/Predis/Commands/HashIncrementBy.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class HashIncrementBy extends Command { - public function getId() { +class HashIncrementBy extends Command +{ + public function getId() + { return 'HINCRBY'; } } diff --git a/lib/Predis/Commands/HashKeys.php b/lib/Predis/Commands/HashKeys.php index 23fcd18a..4f93a3da 100644 --- a/lib/Predis/Commands/HashKeys.php +++ b/lib/Predis/Commands/HashKeys.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class HashKeys extends Command { - public function getId() { +class HashKeys extends Command +{ + public function getId() + { return 'HKEYS'; } } diff --git a/lib/Predis/Commands/HashLength.php b/lib/Predis/Commands/HashLength.php index 1da170a3..6e20a681 100644 --- a/lib/Predis/Commands/HashLength.php +++ b/lib/Predis/Commands/HashLength.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class HashLength extends Command { - public function getId() { +class HashLength extends Command +{ + public function getId() + { return 'HLEN'; } } diff --git a/lib/Predis/Commands/HashSet.php b/lib/Predis/Commands/HashSet.php index 0436f710..f4ca44a3 100644 --- a/lib/Predis/Commands/HashSet.php +++ b/lib/Predis/Commands/HashSet.php @@ -3,11 +3,13 @@ namespace Predis\Commands; class HashSet extends Command { - public function getId() { + public function getId() + { return 'HSET'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/HashSetMultiple.php b/lib/Predis/Commands/HashSetMultiple.php index bf1d1793..a5e78017 100644 --- a/lib/Predis/Commands/HashSetMultiple.php +++ b/lib/Predis/Commands/HashSetMultiple.php @@ -2,21 +2,27 @@ namespace Predis\Commands; -class HashSetMultiple extends Command { - public function getId() { +class HashSetMultiple extends Command +{ + public function getId() + { return 'HMSET'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (count($arguments) === 2 && is_array($arguments[1])) { $flattenedKVs = array($arguments[0]); $args = $arguments[1]; + foreach ($args as $k => $v) { $flattenedKVs[] = $k; $flattenedKVs[] = $v; } + return $flattenedKVs; } + return $arguments; } } diff --git a/lib/Predis/Commands/HashSetPreserve.php b/lib/Predis/Commands/HashSetPreserve.php index 5f0cfb01..91dd1f82 100644 --- a/lib/Predis/Commands/HashSetPreserve.php +++ b/lib/Predis/Commands/HashSetPreserve.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class HashSetPreserve extends Command { - public function getId() { +class HashSetPreserve extends Command +{ + public function getId() + { return 'HSETNX'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/HashValues.php b/lib/Predis/Commands/HashValues.php index 03e16a68..f6a5b400 100644 --- a/lib/Predis/Commands/HashValues.php +++ b/lib/Predis/Commands/HashValues.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class HashValues extends Command { - public function getId() { +class HashValues extends Command +{ + public function getId() + { return 'HVALS'; } } diff --git a/lib/Predis/Commands/ICommand.php b/lib/Predis/Commands/ICommand.php index f1a43a2a..330f8c8d 100644 --- a/lib/Predis/Commands/ICommand.php +++ b/lib/Predis/Commands/ICommand.php @@ -4,7 +4,8 @@ namespace Predis\Commands; use Predis\Distribution\INodeKeyGenerator; -interface ICommand { +interface ICommand +{ public function getId(); public function getHash(INodeKeyGenerator $distributor); public function setArguments(Array $arguments); diff --git a/lib/Predis/Commands/KeyDelete.php b/lib/Predis/Commands/KeyDelete.php index 152782d6..ac8492b7 100644 --- a/lib/Predis/Commands/KeyDelete.php +++ b/lib/Predis/Commands/KeyDelete.php @@ -4,24 +4,30 @@ namespace Predis\Commands; use Predis\Helpers; -class KeyDelete extends Command { - public function getId() { +class KeyDelete extends Command +{ + public function getId() + { return 'DEL'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterArrayArguments($arguments); } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { $args = $this->getArguments(); if (count($args) === 1) { return true; } + return $this->checkSameHashForKeys($args); } } diff --git a/lib/Predis/Commands/KeyExists.php b/lib/Predis/Commands/KeyExists.php index 9845e641..580705da 100644 --- a/lib/Predis/Commands/KeyExists.php +++ b/lib/Predis/Commands/KeyExists.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeyExists extends Command { - public function getId() { +class KeyExists extends Command +{ + public function getId() + { return 'EXISTS'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/KeyExpire.php b/lib/Predis/Commands/KeyExpire.php index a7a1fe2e..8540ec72 100644 --- a/lib/Predis/Commands/KeyExpire.php +++ b/lib/Predis/Commands/KeyExpire.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeyExpire extends Command { - public function getId() { +class KeyExpire extends Command +{ + public function getId() + { return 'EXPIRE'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/KeyExpireAt.php b/lib/Predis/Commands/KeyExpireAt.php index b6cec939..da2eb91d 100644 --- a/lib/Predis/Commands/KeyExpireAt.php +++ b/lib/Predis/Commands/KeyExpireAt.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeyExpireAt extends Command { - public function getId() { +class KeyExpireAt extends Command +{ + public function getId() + { return 'EXPIREAT'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/KeyKeys.php b/lib/Predis/Commands/KeyKeys.php index 28e29b33..1156f769 100644 --- a/lib/Predis/Commands/KeyKeys.php +++ b/lib/Predis/Commands/KeyKeys.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeyKeys extends Command { - public function getId() { +class KeyKeys extends Command +{ + public function getId() + { return 'KEYS'; } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/KeyKeysV12x.php b/lib/Predis/Commands/KeyKeysV12x.php index a9fa8b67..5d75255b 100644 --- a/lib/Predis/Commands/KeyKeysV12x.php +++ b/lib/Predis/Commands/KeyKeysV12x.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class KeyKeysV12x extends KeyKeys { - public function parseResponse($data) { +class KeyKeysV12x extends KeyKeys +{ + public function parseResponse($data) + { return explode(' ', $data); } } diff --git a/lib/Predis/Commands/KeyMove.php b/lib/Predis/Commands/KeyMove.php index 38ac9536..4fcb4076 100644 --- a/lib/Predis/Commands/KeyMove.php +++ b/lib/Predis/Commands/KeyMove.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class KeyMove extends Command { - public function getId() { +class KeyMove extends Command +{ + public function getId() + { return 'MOVE'; } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/KeyPersist.php b/lib/Predis/Commands/KeyPersist.php index 24eb21d5..a9039978 100644 --- a/lib/Predis/Commands/KeyPersist.php +++ b/lib/Predis/Commands/KeyPersist.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeyPersist extends Command { - public function getId() { +class KeyPersist extends Command +{ + public function getId() + { return 'PERSIST'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/KeyRandom.php b/lib/Predis/Commands/KeyRandom.php index 4b2afdfb..5617924f 100644 --- a/lib/Predis/Commands/KeyRandom.php +++ b/lib/Predis/Commands/KeyRandom.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class KeyRandom extends Command { - public function getId() { +class KeyRandom extends Command +{ + public function getId() + { return 'RANDOMKEY'; } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return $data !== '' ? $data : null; } } diff --git a/lib/Predis/Commands/KeyRename.php b/lib/Predis/Commands/KeyRename.php index 103b4f7b..9c8c98e6 100644 --- a/lib/Predis/Commands/KeyRename.php +++ b/lib/Predis/Commands/KeyRename.php @@ -3,15 +3,18 @@ namespace Predis\Commands; class KeyRename extends Command { - public function getId() { + public function getId() + { return 'RENAME'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/KeyRenamePreserve.php b/lib/Predis/Commands/KeyRenamePreserve.php index 337317bb..5cf0bd2b 100644 --- a/lib/Predis/Commands/KeyRenamePreserve.php +++ b/lib/Predis/Commands/KeyRenamePreserve.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeyRenamePreserve extends KeyRename { - public function getId() { +class KeyRenamePreserve extends KeyRename +{ + public function getId() + { return 'RENAMENX'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/KeySort.php b/lib/Predis/Commands/KeySort.php index cbad4a77..9b03dafd 100644 --- a/lib/Predis/Commands/KeySort.php +++ b/lib/Predis/Commands/KeySort.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class KeySort extends Command { - public function getId() { +class KeySort extends Command +{ + public function getId() + { return 'SORT'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (count($arguments) === 1) { return $arguments; } @@ -19,6 +22,7 @@ class KeySort extends Command { $query[] = 'BY'; $query[] = $sortParams['BY']; } + if (isset($sortParams['GET'])) { $getargs = $sortParams['GET']; if (is_array($getargs)) { @@ -32,6 +36,7 @@ class KeySort extends Command { $query[] = $getargs; } } + if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT']) && count($sortParams['LIMIT']) == 2) { @@ -39,12 +44,15 @@ class KeySort extends Command { $query[] = $sortParams['LIMIT'][0]; $query[] = $sortParams['LIMIT'][1]; } + if (isset($sortParams['SORT'])) { $query[] = strtoupper($sortParams['SORT']); } + if (isset($sortParams['ALPHA']) && $sortParams['ALPHA'] == true) { $query[] = 'ALPHA'; } + if (isset($sortParams['STORE'])) { $query[] = 'STORE'; $query[] = $sortParams['STORE']; @@ -53,8 +61,10 @@ class KeySort extends Command { return $query; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { $arguments[0] = "$prefix{$arguments[0]}"; + if (($count = count($arguments)) > 1) { for ($i = 1; $i < $count; $i++) { switch ($arguments[$i]) { @@ -62,18 +72,21 @@ class KeySort extends Command { case 'STORE': $arguments[$i] = "$prefix{$arguments[++$i]}"; break; + case 'GET': $value = $arguments[++$i]; if ($value !== '#') { $arguments[$i] = "$prefix$value"; } break; + case 'LIMIT'; $i += 2; break; } } } + return $arguments; } } diff --git a/lib/Predis/Commands/KeyTimeToLive.php b/lib/Predis/Commands/KeyTimeToLive.php index 5f0c347d..c1ccc337 100644 --- a/lib/Predis/Commands/KeyTimeToLive.php +++ b/lib/Predis/Commands/KeyTimeToLive.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class KeyTimeToLive extends Command { - public function getId() { +class KeyTimeToLive extends Command +{ + public function getId() + { return 'TTL'; } } diff --git a/lib/Predis/Commands/KeyType.php b/lib/Predis/Commands/KeyType.php index d7f8fe1e..a32f0865 100644 --- a/lib/Predis/Commands/KeyType.php +++ b/lib/Predis/Commands/KeyType.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class KeyType extends Command { - public function getId() { +class KeyType extends Command +{ + public function getId() + { return 'TYPE'; } } diff --git a/lib/Predis/Commands/ListIndex.php b/lib/Predis/Commands/ListIndex.php index 177a3009..9552e22f 100644 --- a/lib/Predis/Commands/ListIndex.php +++ b/lib/Predis/Commands/ListIndex.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListIndex extends Command { - public function getId() { +class ListIndex extends Command +{ + public function getId() + { return 'LINDEX'; } } diff --git a/lib/Predis/Commands/ListInsert.php b/lib/Predis/Commands/ListInsert.php index c5420bba..61e880fb 100644 --- a/lib/Predis/Commands/ListInsert.php +++ b/lib/Predis/Commands/ListInsert.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListInsert extends Command { - public function getId() { +class ListInsert extends Command +{ + public function getId() + { return 'LINSERT'; } } diff --git a/lib/Predis/Commands/ListLength.php b/lib/Predis/Commands/ListLength.php index 28fa647e..9c0fbdfd 100644 --- a/lib/Predis/Commands/ListLength.php +++ b/lib/Predis/Commands/ListLength.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListLength extends Command { - public function getId() { +class ListLength extends Command +{ + public function getId() + { return 'LLEN'; } } diff --git a/lib/Predis/Commands/ListPopFirst.php b/lib/Predis/Commands/ListPopFirst.php index 4399d38d..d89d6a80 100644 --- a/lib/Predis/Commands/ListPopFirst.php +++ b/lib/Predis/Commands/ListPopFirst.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListPopFirst extends Command { - public function getId() { +class ListPopFirst extends Command +{ + public function getId() + { return 'LPOP'; } } diff --git a/lib/Predis/Commands/ListPopFirstBlocking.php b/lib/Predis/Commands/ListPopFirstBlocking.php index 46f83cad..62270745 100644 --- a/lib/Predis/Commands/ListPopFirstBlocking.php +++ b/lib/Predis/Commands/ListPopFirstBlocking.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ListPopFirstBlocking extends Command { - public function getId() { +class ListPopFirstBlocking extends Command +{ + public function getId() + { return 'BLPOP'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::skipLastArgument($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return $this->checkSameHashForKeys( array_slice(($args = $this->getArguments()), 0, count($args) - 1) ); diff --git a/lib/Predis/Commands/ListPopLast.php b/lib/Predis/Commands/ListPopLast.php index 792df506..d51d91d6 100644 --- a/lib/Predis/Commands/ListPopLast.php +++ b/lib/Predis/Commands/ListPopLast.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListPopLast extends Command { - public function getId() { +class ListPopLast extends Command +{ + public function getId() + { return 'RPOP'; } } diff --git a/lib/Predis/Commands/ListPopLastBlocking.php b/lib/Predis/Commands/ListPopLastBlocking.php index 22b148cd..e279e0c2 100644 --- a/lib/Predis/Commands/ListPopLastBlocking.php +++ b/lib/Predis/Commands/ListPopLastBlocking.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListPopLastBlocking extends ListPopFirstBlocking { - public function getId() { +class ListPopLastBlocking extends ListPopFirstBlocking +{ + public function getId() + { return 'BRPOP'; } } diff --git a/lib/Predis/Commands/ListPopLastPushHead.php b/lib/Predis/Commands/ListPopLastPushHead.php index 13d9c112..b59b4ddd 100644 --- a/lib/Predis/Commands/ListPopLastPushHead.php +++ b/lib/Predis/Commands/ListPopLastPushHead.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ListPopLastPushHead extends Command { - public function getId() { +class ListPopLastPushHead extends Command +{ + public function getId() + { return 'RPOPLPUSH'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return $this->checkSameHashForKeys($this->getArguments()); } } diff --git a/lib/Predis/Commands/ListPopLastPushHeadBlocking.php b/lib/Predis/Commands/ListPopLastPushHeadBlocking.php index 87608c66..91655bf3 100644 --- a/lib/Predis/Commands/ListPopLastPushHeadBlocking.php +++ b/lib/Predis/Commands/ListPopLastPushHeadBlocking.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ListPopLastPushHeadBlocking extends Command { - public function getId() { +class ListPopLastPushHeadBlocking extends Command +{ + public function getId() + { return 'BRPOPLPUSH'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::skipLastArgument($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return $this->checkSameHashForKeys( array_slice($args = $this->getArguments(), 0, count($args) - 1) ); diff --git a/lib/Predis/Commands/ListPushHead.php b/lib/Predis/Commands/ListPushHead.php index 1efd0009..cd7c5f26 100644 --- a/lib/Predis/Commands/ListPushHead.php +++ b/lib/Predis/Commands/ListPushHead.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListPushHead extends ListPushTail { - public function getId() { +class ListPushHead extends ListPushTail +{ + public function getId() + { return 'LPUSH'; } } diff --git a/lib/Predis/Commands/ListPushHeadX.php b/lib/Predis/Commands/ListPushHeadX.php index 55ad1689..dc65743c 100644 --- a/lib/Predis/Commands/ListPushHeadX.php +++ b/lib/Predis/Commands/ListPushHeadX.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListPushHeadX extends Command { - public function getId() { +class ListPushHeadX extends Command +{ + public function getId() + { return 'LPUSHX'; } } diff --git a/lib/Predis/Commands/ListPushTail.php b/lib/Predis/Commands/ListPushTail.php index 463cba24..92bea1d0 100644 --- a/lib/Predis/Commands/ListPushTail.php +++ b/lib/Predis/Commands/ListPushTail.php @@ -4,12 +4,15 @@ namespace Predis\Commands; use Predis\Helpers; -class ListPushTail extends Command { - public function getId() { +class ListPushTail extends Command +{ + public function getId() + { return 'RPUSH'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } } diff --git a/lib/Predis/Commands/ListPushTailX.php b/lib/Predis/Commands/ListPushTailX.php index 55225ac2..ea386175 100644 --- a/lib/Predis/Commands/ListPushTailX.php +++ b/lib/Predis/Commands/ListPushTailX.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListPushTailX extends Command { - public function getId() { +class ListPushTailX extends Command +{ + public function getId() + { return 'RPUSHX'; } } diff --git a/lib/Predis/Commands/ListRange.php b/lib/Predis/Commands/ListRange.php index 5f2a14cd..4da76d61 100644 --- a/lib/Predis/Commands/ListRange.php +++ b/lib/Predis/Commands/ListRange.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListRange extends Command { - public function getId() { +class ListRange extends Command +{ + public function getId() + { return 'LRANGE'; } } diff --git a/lib/Predis/Commands/ListRemove.php b/lib/Predis/Commands/ListRemove.php index c28ccaa4..8a32baa5 100644 --- a/lib/Predis/Commands/ListRemove.php +++ b/lib/Predis/Commands/ListRemove.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListRemove extends Command { - public function getId() { +class ListRemove extends Command +{ + public function getId() + { return 'LREM'; } } diff --git a/lib/Predis/Commands/ListSet.php b/lib/Predis/Commands/ListSet.php index e39a4c47..ed8ae576 100644 --- a/lib/Predis/Commands/ListSet.php +++ b/lib/Predis/Commands/ListSet.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListSet extends Command { - public function getId() { +class ListSet extends Command +{ + public function getId() + { return 'LSET'; } } diff --git a/lib/Predis/Commands/ListTrim.php b/lib/Predis/Commands/ListTrim.php index b7bb4d75..d91f6a74 100644 --- a/lib/Predis/Commands/ListTrim.php +++ b/lib/Predis/Commands/ListTrim.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ListTrim extends Command { - public function getId() { +class ListTrim extends Command +{ + public function getId() + { return 'LTRIM'; } } diff --git a/lib/Predis/Commands/PrefixHelpers.php b/lib/Predis/Commands/PrefixHelpers.php index 8e682c81..397776b3 100644 --- a/lib/Predis/Commands/PrefixHelpers.php +++ b/lib/Predis/Commands/PrefixHelpers.php @@ -2,19 +2,24 @@ namespace Predis\Commands; -class PrefixHelpers { - public static function multipleKeys(Array $arguments, $prefix) { +class PrefixHelpers +{ + public static function multipleKeys(Array $arguments, $prefix) + { foreach ($arguments as &$key) { $key = "$prefix$key"; } + return $arguments; } - public static function skipLastArgument(Array $arguments, $prefix) { + public static function skipLastArgument(Array $arguments, $prefix) + { $length = count($arguments); for ($i = 0; $i < $length - 1; $i++) { $arguments[$i] = "$prefix{$arguments[$i]}"; } + return $arguments; } } diff --git a/lib/Predis/Commands/Processors/ICommandProcessor.php b/lib/Predis/Commands/Processors/ICommandProcessor.php index 3b4f8873..3101d266 100644 --- a/lib/Predis/Commands/Processors/ICommandProcessor.php +++ b/lib/Predis/Commands/Processors/ICommandProcessor.php @@ -4,6 +4,7 @@ namespace Predis\Commands\Processors; use Predis\Commands\ICommand; -interface ICommandProcessor { +interface ICommandProcessor +{ public function process(ICommand $command); } diff --git a/lib/Predis/Commands/Processors/ICommandProcessorChain.php b/lib/Predis/Commands/Processors/ICommandProcessorChain.php index f83c4d0a..04c01650 100644 --- a/lib/Predis/Commands/Processors/ICommandProcessorChain.php +++ b/lib/Predis/Commands/Processors/ICommandProcessorChain.php @@ -2,8 +2,8 @@ namespace Predis\Commands\Processors; -interface ICommandProcessorChain - extends ICommandProcessor, \IteratorAggregate, \Countable { +interface ICommandProcessorChain extends ICommandProcessor, \IteratorAggregate, \Countable +{ public function add(ICommandProcessor $preprocessor); public function remove(ICommandProcessor $preprocessor); diff --git a/lib/Predis/Commands/Processors/IProcessingSupport.php b/lib/Predis/Commands/Processors/IProcessingSupport.php index 46f0d39b..096a7dc0 100644 --- a/lib/Predis/Commands/Processors/IProcessingSupport.php +++ b/lib/Predis/Commands/Processors/IProcessingSupport.php @@ -2,7 +2,8 @@ namespace Predis\Commands\Processors; -interface IProcessingSupport { +interface IProcessingSupport +{ public function setProcessor(ICommandProcessor $processor); public function getProcessor(); } diff --git a/lib/Predis/Commands/Processors/KeyPrefixProcessor.php b/lib/Predis/Commands/Processors/KeyPrefixProcessor.php index d43cd1b1..05878076 100644 --- a/lib/Predis/Commands/Processors/KeyPrefixProcessor.php +++ b/lib/Predis/Commands/Processors/KeyPrefixProcessor.php @@ -4,22 +4,27 @@ namespace Predis\Commands\Processors; use Predis\Commands\ICommand; -class KeyPrefixProcessor implements ICommandProcessor { +class KeyPrefixProcessor implements ICommandProcessor +{ private $_prefix; - public function __construct($prefix) { + public function __construct($prefix) + { $this->setPrefix($prefix); } - public function setPrefix($prefix) { + public function setPrefix($prefix) + { $this->_prefix = $prefix; } - public function getPrefix() { + public function getPrefix() + { return $this->_prefix; } - public function process(ICommand $command) { + public function process(ICommand $command) + { $command->prefixKeys($this->_prefix); } } diff --git a/lib/Predis/Commands/Processors/ProcessorChain.php b/lib/Predis/Commands/Processors/ProcessorChain.php index 65afb6fb..a39ce115 100644 --- a/lib/Predis/Commands/Processors/ProcessorChain.php +++ b/lib/Predis/Commands/Processors/ProcessorChain.php @@ -4,64 +4,77 @@ namespace Predis\Commands\Processors; use Predis\Commands\ICommand; -class ProcessorChain implements ICommandProcessorChain, \ArrayAccess { +class ProcessorChain implements ICommandProcessorChain, \ArrayAccess +{ private $_processors; - public function __construct($processors = array()) { + public function __construct($processors = array()) + { foreach ($processors as $processor) { $this->add($processor); } } - public function add(ICommandProcessor $processor) { + public function add(ICommandProcessor $processor) + { $this->_processors[] = $processor; } - public function remove(ICommandProcessor $processor) { + public function remove(ICommandProcessor $processor) + { $index = array_search($processor, $this->_processors, true); if ($index !== false) { - unset($this->_processors); + unset($this[$index]); } } - public function process(ICommand $command) { + public function process(ICommand $command) + { $count = count($this->_processors); for ($i = 0; $i < $count; $i++) { $this->_processors[$i]->process($command); } } - public function getProcessors() { + public function getProcessors() + { return $this->_processors; } - public function getIterator() { + public function getIterator() + { return new \ArrayIterator($this->_processors); } - public function count() { + public function count() + { return count($this->_processors); } - public function offsetExists($index) { + public function offsetExists($index) + { return isset($this->_processors[$index]); } - public function offsetGet($index) { + public function offsetGet($index) + { return $this->_processors[$index]; } - public function offsetSet($index, $processor) { + public function offsetSet($index, $processor) + { if (!$processor instanceof ICommandProcessor) { throw new \InvalidArgumentException( 'A processor chain can hold only instances of classes implementing '. 'the Predis\Commands\Preprocessors\ICommandProcessor interface' ); } + $this->_processors[$index] = $processor; } - public function offsetUnset($index) { + public function offsetUnset($index) + { unset($this->_processors[$index]); } } diff --git a/lib/Predis/Commands/PubSubPublish.php b/lib/Predis/Commands/PubSubPublish.php index c28b4c7e..3998e9a3 100644 --- a/lib/Predis/Commands/PubSubPublish.php +++ b/lib/Predis/Commands/PubSubPublish.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class PubSubPublish extends Command { - public function getId() { +class PubSubPublish extends Command +{ + public function getId() + { return 'PUBLISH'; } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/PubSubSubscribe.php b/lib/Predis/Commands/PubSubSubscribe.php index 67c04adb..2d190ab5 100644 --- a/lib/Predis/Commands/PubSubSubscribe.php +++ b/lib/Predis/Commands/PubSubSubscribe.php @@ -4,20 +4,25 @@ namespace Predis\Commands; use Predis\Helpers; -class PubSubSubscribe extends Command { - public function getId() { +class PubSubSubscribe extends Command +{ + public function getId() + { return 'SUBSCRIBE'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterArrayArguments($arguments); } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/PubSubSubscribeByPattern.php b/lib/Predis/Commands/PubSubSubscribeByPattern.php index 1af67b1d..f33f4307 100644 --- a/lib/Predis/Commands/PubSubSubscribeByPattern.php +++ b/lib/Predis/Commands/PubSubSubscribeByPattern.php @@ -4,8 +4,10 @@ namespace Predis\Commands; use Predis\Helpers; -class PubSubSubscribeByPattern extends PubSubSubscribe { - public function getId() { +class PubSubSubscribeByPattern extends PubSubSubscribe +{ + public function getId() + { return 'PSUBSCRIBE'; } } diff --git a/lib/Predis/Commands/PubSubUnsubscribe.php b/lib/Predis/Commands/PubSubUnsubscribe.php index 862ee9d4..9acdee14 100644 --- a/lib/Predis/Commands/PubSubUnsubscribe.php +++ b/lib/Predis/Commands/PubSubUnsubscribe.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class PubSubUnsubscribe extends Command { - public function getId() { +class PubSubUnsubscribe extends Command +{ + public function getId() + { return 'UNSUBSCRIBE'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/PubSubUnsubscribeByPattern.php b/lib/Predis/Commands/PubSubUnsubscribeByPattern.php index 36e6e28e..a0302a7e 100644 --- a/lib/Predis/Commands/PubSubUnsubscribeByPattern.php +++ b/lib/Predis/Commands/PubSubUnsubscribeByPattern.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class PubSubUnsubscribeByPattern extends PubSubUnsubscribe { - public function getId() { +class PubSubUnsubscribeByPattern extends PubSubUnsubscribe +{ + public function getId() + { return 'PUNSUBSCRIBE'; } } diff --git a/lib/Predis/Commands/ScriptedCommand.php b/lib/Predis/Commands/ScriptedCommand.php index 8224a1cc..974114e7 100644 --- a/lib/Predis/Commands/ScriptedCommand.php +++ b/lib/Predis/Commands/ScriptedCommand.php @@ -2,20 +2,24 @@ namespace Predis\Commands; -abstract class ScriptedCommand extends ServerEval { +abstract class ScriptedCommand extends ServerEval +{ public abstract function getScript(); - protected function keysCount() { + protected function keysCount() + { // The default behaviour for the base class is to use all the arguments // passed to a scripted command to populate the KEYS table in Lua. return count($this->getArguments()); } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return array_merge(array($this->getScript(), $this->keysCount()), $arguments); } - protected function getKeys() { + protected function getKeys() + { return array_slice($this->getArguments(), 2, $this->keysCount()); } } diff --git a/lib/Predis/Commands/ServerBackgroundRewriteAOF.php b/lib/Predis/Commands/ServerBackgroundRewriteAOF.php index 19477c2a..8a0b5f09 100644 --- a/lib/Predis/Commands/ServerBackgroundRewriteAOF.php +++ b/lib/Predis/Commands/ServerBackgroundRewriteAOF.php @@ -2,20 +2,25 @@ namespace Predis\Commands; -class ServerBackgroundRewriteAOF extends Command { - public function getId() { +class ServerBackgroundRewriteAOF extends Command +{ + public function getId() + { return 'BGREWRITEAOF'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return $data == 'Background append only file rewriting started'; } } diff --git a/lib/Predis/Commands/ServerBackgroundSave.php b/lib/Predis/Commands/ServerBackgroundSave.php index 85f02e26..c7760e4a 100644 --- a/lib/Predis/Commands/ServerBackgroundSave.php +++ b/lib/Predis/Commands/ServerBackgroundSave.php @@ -2,23 +2,29 @@ namespace Predis\Commands; -class ServerBackgroundSave extends Command { - public function getId() { +class ServerBackgroundSave extends Command +{ + public function getId() + { return 'BGSAVE'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { if ($data == 'Background saving started') { return true; } + return $data; } } diff --git a/lib/Predis/Commands/ServerClient.php b/lib/Predis/Commands/ServerClient.php index 90d32001..82426eb0 100644 --- a/lib/Predis/Commands/ServerClient.php +++ b/lib/Predis/Commands/ServerClient.php @@ -2,32 +2,40 @@ namespace Predis\Commands; -class ServerClient extends Command { - public function getId() { +class ServerClient extends Command +{ + public function getId() + { return 'CLIENT'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { $args = array_change_key_case($this->getArguments(), CASE_UPPER); switch (strtoupper($args[0])) { case 'LIST': return $this->parseClientList($data); + case 'KILL': default: return $data; } } - protected function parseClientList($data) { + protected function parseClientList($data) + { $clients = array(); + foreach (explode("\n", $data, -1) as $clientData) { $client = array(); foreach (explode(' ', $clientData) as $kv) { @@ -36,6 +44,7 @@ class ServerClient extends Command { } $clients[] = $client; } + return $clients; } } diff --git a/lib/Predis/Commands/ServerConfig.php b/lib/Predis/Commands/ServerConfig.php index 1f78e9b8..b144f3ea 100644 --- a/lib/Predis/Commands/ServerConfig.php +++ b/lib/Predis/Commands/ServerConfig.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerConfig extends Command { - public function getId() { +class ServerConfig extends Command +{ + public function getId() + { return 'CONFIG'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerDatabaseSize.php b/lib/Predis/Commands/ServerDatabaseSize.php index 8e8e64b2..630929e6 100644 --- a/lib/Predis/Commands/ServerDatabaseSize.php +++ b/lib/Predis/Commands/ServerDatabaseSize.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerDatabaseSize extends Command { - public function getId() { +class ServerDatabaseSize extends Command +{ + public function getId() + { return 'DBSIZE'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerEval.php b/lib/Predis/Commands/ServerEval.php index f20ca61c..b4076f7c 100644 --- a/lib/Predis/Commands/ServerEval.php +++ b/lib/Predis/Commands/ServerEval.php @@ -2,20 +2,26 @@ namespace Predis\Commands; -class ServerEval extends Command { - public function getId() { +class ServerEval extends Command +{ + public function getId() + { return 'EVAL'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { $arguments = $this->getArguments(); + for ($i = 2; $i < $arguments[1] + 2; $i++) { $arguments[$i] = "$prefix{$arguments[$i]}"; } + return $arguments; } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerEvalSHA.php b/lib/Predis/Commands/ServerEvalSHA.php index 56b28e68..6b9bd84d 100644 --- a/lib/Predis/Commands/ServerEvalSHA.php +++ b/lib/Predis/Commands/ServerEvalSHA.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ServerEvalSHA extends ServerEval { - public function getId() { +class ServerEvalSHA extends ServerEval +{ + public function getId() + { return 'EVALSHA'; } } diff --git a/lib/Predis/Commands/ServerFlushAll.php b/lib/Predis/Commands/ServerFlushAll.php index be695a5f..8cb180a9 100644 --- a/lib/Predis/Commands/ServerFlushAll.php +++ b/lib/Predis/Commands/ServerFlushAll.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerFlushAll extends Command { - public function getId() { +class ServerFlushAll extends Command +{ + public function getId() + { return 'FLUSHALL'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerFlushDatabase.php b/lib/Predis/Commands/ServerFlushDatabase.php index 2443990f..553f0e89 100644 --- a/lib/Predis/Commands/ServerFlushDatabase.php +++ b/lib/Predis/Commands/ServerFlushDatabase.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerFlushDatabase extends Command { - public function getId() { +class ServerFlushDatabase extends Command +{ + public function getId() + { return 'FLUSHDB'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerInfo.php b/lib/Predis/Commands/ServerInfo.php index 4d1f3459..d9b73dcf 100644 --- a/lib/Predis/Commands/ServerInfo.php +++ b/lib/Predis/Commands/ServerInfo.php @@ -2,27 +2,35 @@ namespace Predis\Commands; -class ServerInfo extends Command { - public function getId() { +class ServerInfo extends Command +{ + public function getId() + { return 'INFO'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { $info = array(); $infoLines = explode("\r\n", $data, -1); + foreach ($infoLines as $row) { @list($k, $v) = explode(':', $row); + if ($row === '' || !isset($v)) { continue; } + if (!preg_match('/^db\d+$/', $k)) { if ($k === 'allocation_stats') { $info[$k] = $this->parseAllocationStats($v); @@ -34,22 +42,29 @@ class ServerInfo extends Command { $info[$k] = $this->parseDatabaseStats($v); } } + return $info; } - protected function parseDatabaseStats($str) { + protected function parseDatabaseStats($str) + { $db = array(); + foreach (explode(',', $str) as $dbvar) { list($dbvk, $dbvv) = explode('=', $dbvar); $db[trim($dbvk)] = $dbvv; } + return $db; } - protected function parseAllocationStats($str) { + protected function parseAllocationStats($str) + { $stats = array(); + foreach (explode(',', $str) as $kv) { @list($size, $objects, $extra) = explode('=', $kv); + // hack to prevent incorrect values when parsing the >=256 key if (isset($extra)) { $size = ">=$objects"; @@ -57,6 +72,7 @@ class ServerInfo extends Command { } $stats[$size] = $objects; } + return $stats; } } diff --git a/lib/Predis/Commands/ServerInfoV26x.php b/lib/Predis/Commands/ServerInfoV26x.php index b8087245..cf842576 100644 --- a/lib/Predis/Commands/ServerInfoV26x.php +++ b/lib/Predis/Commands/ServerInfoV26x.php @@ -2,21 +2,27 @@ namespace Predis\Commands; -class ServerInfoV26x extends ServerInfo { - public function parseResponse($data) { - $info = array(); - $current = null; +class ServerInfoV26x extends ServerInfo +{ + public function parseResponse($data) + { + $info = array(); + $current = null; $infoLines = explode("\r\n", $data, -1); + foreach ($infoLines as $row) { if ($row === '') { continue; } + if (preg_match('/^# (\w+)$/', $row, $matches)) { $info[$matches[1]] = array(); $current = &$info[$matches[1]]; continue; } + list($k, $v) = explode(':', $row); + if (!preg_match('/^db\d+$/', $k)) { if ($k === 'allocation_stats') { $current[$k] = $this->parseAllocationStats($v); @@ -28,6 +34,7 @@ class ServerInfoV26x extends ServerInfo { $current[$k] = $this->parseDatabaseStats($v); } } + return $info; } } diff --git a/lib/Predis/Commands/ServerLastSave.php b/lib/Predis/Commands/ServerLastSave.php index 3f430c54..dfdeaa6e 100644 --- a/lib/Predis/Commands/ServerLastSave.php +++ b/lib/Predis/Commands/ServerLastSave.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerLastSave extends Command { - public function getId() { +class ServerLastSave extends Command +{ + public function getId() + { return 'LASTSAVE'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerMonitor.php b/lib/Predis/Commands/ServerMonitor.php index 55637e8f..cd5f6b14 100644 --- a/lib/Predis/Commands/ServerMonitor.php +++ b/lib/Predis/Commands/ServerMonitor.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerMonitor extends Command { - public function getId() { +class ServerMonitor extends Command +{ + public function getId() + { return 'MONITOR'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerObject.php b/lib/Predis/Commands/ServerObject.php index 3081e366..f51d5981 100644 --- a/lib/Predis/Commands/ServerObject.php +++ b/lib/Predis/Commands/ServerObject.php @@ -4,16 +4,20 @@ namespace Predis\Commands; use Predis\Helpers; -class ServerObject extends Command { - public function getId() { +class ServerObject extends Command +{ + public function getId() + { return 'OBJECT'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerSave.php b/lib/Predis/Commands/ServerSave.php index e90a94ba..245a7c82 100644 --- a/lib/Predis/Commands/ServerSave.php +++ b/lib/Predis/Commands/ServerSave.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class ServerSave extends Command { - public function getId() { +class ServerSave extends Command +{ + public function getId() + { return 'SAVE'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerShutdown.php b/lib/Predis/Commands/ServerShutdown.php index 22026332..80a00822 100644 --- a/lib/Predis/Commands/ServerShutdown.php +++ b/lib/Predis/Commands/ServerShutdown.php @@ -2,16 +2,19 @@ namespace Predis\Commands; -class ServerShutdown extends Command { +class ServerShutdown extends Command +{ public function getId() { return 'SHUTDOWN'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/ServerSlaveOf.php b/lib/Predis/Commands/ServerSlaveOf.php index aed87b0f..0d10e5c4 100644 --- a/lib/Predis/Commands/ServerSlaveOf.php +++ b/lib/Predis/Commands/ServerSlaveOf.php @@ -2,23 +2,29 @@ namespace Predis\Commands; -class ServerSlaveOf extends Command { - public function getId() { +class ServerSlaveOf extends Command +{ + public function getId() + { return 'SLAVEOF'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (count($arguments) === 0 || $arguments[0] === 'NO ONE') { return array('NO', 'ONE'); } + return $arguments; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/SetAdd.php b/lib/Predis/Commands/SetAdd.php index 5c95eeb5..a262c2e8 100644 --- a/lib/Predis/Commands/SetAdd.php +++ b/lib/Predis/Commands/SetAdd.php @@ -4,16 +4,20 @@ namespace Predis\Commands; use Predis\Helpers; -class SetAdd extends Command { - public function getId() { +class SetAdd extends Command +{ + public function getId() + { return 'SADD'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/SetCardinality.php b/lib/Predis/Commands/SetCardinality.php index 49f5c138..8c1685c5 100644 --- a/lib/Predis/Commands/SetCardinality.php +++ b/lib/Predis/Commands/SetCardinality.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetCardinality extends Command { - public function getId() { +class SetCardinality extends Command +{ + public function getId() + { return 'SCARD'; } } diff --git a/lib/Predis/Commands/SetDifference.php b/lib/Predis/Commands/SetDifference.php index b4aeed4d..8ebb7bb6 100644 --- a/lib/Predis/Commands/SetDifference.php +++ b/lib/Predis/Commands/SetDifference.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class SetDifference extends SetIntersection { - public function getId() { +class SetDifference extends SetIntersection +{ + public function getId() + { return 'SDIFF'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } } diff --git a/lib/Predis/Commands/SetDifferenceStore.php b/lib/Predis/Commands/SetDifferenceStore.php index 8677110d..b8a2a494 100644 --- a/lib/Predis/Commands/SetDifferenceStore.php +++ b/lib/Predis/Commands/SetDifferenceStore.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetDifferenceStore extends SetIntersectionStore { - public function getId() { +class SetDifferenceStore extends SetIntersectionStore +{ + public function getId() + { return 'SDIFFSTORE'; } } diff --git a/lib/Predis/Commands/SetIntersection.php b/lib/Predis/Commands/SetIntersection.php index 10414e5a..69a48e2e 100644 --- a/lib/Predis/Commands/SetIntersection.php +++ b/lib/Predis/Commands/SetIntersection.php @@ -4,20 +4,25 @@ namespace Predis\Commands; use Predis\Helpers; -class SetIntersection extends Command { - public function getId() { +class SetIntersection extends Command +{ + public function getId() + { return 'SINTER'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterArrayArguments($arguments); } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return $this->checkSameHashForKeys($this->getArguments()); } } diff --git a/lib/Predis/Commands/SetIntersectionStore.php b/lib/Predis/Commands/SetIntersectionStore.php index 1ba38a76..7db7fa71 100644 --- a/lib/Predis/Commands/SetIntersectionStore.php +++ b/lib/Predis/Commands/SetIntersectionStore.php @@ -2,23 +2,29 @@ namespace Predis\Commands; -class SetIntersectionStore extends Command { - public function getId() { +class SetIntersectionStore extends Command +{ + public function getId() + { return 'SINTERSTORE'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (count($arguments) === 2 && is_array($arguments[1])) { return array_merge(array($arguments[0]), $arguments[1]); } + return $arguments; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return $this->checkSameHashForKeys($this->getArguments()); } } diff --git a/lib/Predis/Commands/SetIsMember.php b/lib/Predis/Commands/SetIsMember.php index d1e3557e..94264533 100644 --- a/lib/Predis/Commands/SetIsMember.php +++ b/lib/Predis/Commands/SetIsMember.php @@ -2,12 +2,15 @@ namespace Predis\Commands; -class SetIsMember extends Command { - public function getId() { +class SetIsMember extends Command +{ + public function getId() + { return 'SISMEMBER'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/SetMembers.php b/lib/Predis/Commands/SetMembers.php index ea5383c9..aca651e5 100644 --- a/lib/Predis/Commands/SetMembers.php +++ b/lib/Predis/Commands/SetMembers.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetMembers extends Command { - public function getId() { +class SetMembers extends Command +{ + public function getId() + { return 'SMEMBERS'; } } diff --git a/lib/Predis/Commands/SetMove.php b/lib/Predis/Commands/SetMove.php index 146a86fa..80caa868 100644 --- a/lib/Predis/Commands/SetMove.php +++ b/lib/Predis/Commands/SetMove.php @@ -2,20 +2,25 @@ namespace Predis\Commands; -class SetMove extends Command { - public function getId() { +class SetMove extends Command +{ + public function getId() + { return 'SMOVE'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::skipLastArgument($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/SetPop.php b/lib/Predis/Commands/SetPop.php index 1bef449a..b75bb15c 100644 --- a/lib/Predis/Commands/SetPop.php +++ b/lib/Predis/Commands/SetPop.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetPop extends Command { - public function getId() { +class SetPop extends Command +{ + public function getId() + { return 'SPOP'; } } diff --git a/lib/Predis/Commands/SetRandomMember.php b/lib/Predis/Commands/SetRandomMember.php index 06fe2d77..0bedd910 100644 --- a/lib/Predis/Commands/SetRandomMember.php +++ b/lib/Predis/Commands/SetRandomMember.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetRandomMember extends Command { - public function getId() { +class SetRandomMember extends Command +{ + public function getId() + { return 'SRANDMEMBER'; } } diff --git a/lib/Predis/Commands/SetRemove.php b/lib/Predis/Commands/SetRemove.php index ec300633..80c779a2 100644 --- a/lib/Predis/Commands/SetRemove.php +++ b/lib/Predis/Commands/SetRemove.php @@ -4,16 +4,20 @@ namespace Predis\Commands; use Predis\Helpers; -class SetRemove extends Command { - public function getId() { +class SetRemove extends Command +{ + public function getId() + { return 'SREM'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/SetUnion.php b/lib/Predis/Commands/SetUnion.php index b1cab8e0..92f083c6 100644 --- a/lib/Predis/Commands/SetUnion.php +++ b/lib/Predis/Commands/SetUnion.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetUnion extends SetIntersection { - public function getId() { +class SetUnion extends SetIntersection +{ + public function getId() + { return 'SUNION'; } } diff --git a/lib/Predis/Commands/SetUnionStore.php b/lib/Predis/Commands/SetUnionStore.php index b154532b..8d3cebb3 100644 --- a/lib/Predis/Commands/SetUnionStore.php +++ b/lib/Predis/Commands/SetUnionStore.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class SetUnionStore extends SetIntersectionStore { - public function getId() { +class SetUnionStore extends SetIntersectionStore +{ + public function getId() + { return 'SUNIONSTORE'; } } diff --git a/lib/Predis/Commands/StringAppend.php b/lib/Predis/Commands/StringAppend.php index 0a76b875..a57beb65 100644 --- a/lib/Predis/Commands/StringAppend.php +++ b/lib/Predis/Commands/StringAppend.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringAppend extends Command { - public function getId() { +class StringAppend extends Command +{ + public function getId() + { return 'APPEND'; } } diff --git a/lib/Predis/Commands/StringDecrement.php b/lib/Predis/Commands/StringDecrement.php index fe93c568..647b1c8f 100644 --- a/lib/Predis/Commands/StringDecrement.php +++ b/lib/Predis/Commands/StringDecrement.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringDecrement extends Command { - public function getId() { +class StringDecrement extends Command +{ + public function getId() + { return 'DECR'; } } diff --git a/lib/Predis/Commands/StringDecrementBy.php b/lib/Predis/Commands/StringDecrementBy.php index fcca7ab9..59ca5ba4 100644 --- a/lib/Predis/Commands/StringDecrementBy.php +++ b/lib/Predis/Commands/StringDecrementBy.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringDecrementBy extends Command { - public function getId() { +class StringDecrementBy extends Command +{ + public function getId() + { return 'DECRBY'; } } diff --git a/lib/Predis/Commands/StringGet.php b/lib/Predis/Commands/StringGet.php index 63991a4a..648fb01b 100644 --- a/lib/Predis/Commands/StringGet.php +++ b/lib/Predis/Commands/StringGet.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringGet extends Command { - public function getId() { +class StringGet extends Command +{ + public function getId() + { return 'GET'; } } diff --git a/lib/Predis/Commands/StringGetBit.php b/lib/Predis/Commands/StringGetBit.php index 1ad3068e..11209d4d 100644 --- a/lib/Predis/Commands/StringGetBit.php +++ b/lib/Predis/Commands/StringGetBit.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringGetBit extends Command { - public function getId() { +class StringGetBit extends Command +{ + public function getId() + { return 'GETBIT'; } } diff --git a/lib/Predis/Commands/StringGetMultiple.php b/lib/Predis/Commands/StringGetMultiple.php index 7771dabe..af2e2bf4 100644 --- a/lib/Predis/Commands/StringGetMultiple.php +++ b/lib/Predis/Commands/StringGetMultiple.php @@ -4,20 +4,25 @@ namespace Predis\Commands; use Predis\Helpers; -class StringGetMultiple extends Command { - public function getId() { +class StringGetMultiple extends Command +{ + public function getId() + { return 'MGET'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterArrayArguments($arguments); } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return $this->checkSameHashForKeys($this->getArguments()); } } diff --git a/lib/Predis/Commands/StringGetRange.php b/lib/Predis/Commands/StringGetRange.php index 6f84abbd..0631b653 100644 --- a/lib/Predis/Commands/StringGetRange.php +++ b/lib/Predis/Commands/StringGetRange.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringGetRange extends Command { - public function getId() { +class StringGetRange extends Command +{ + public function getId() + { return 'GETRANGE'; } } diff --git a/lib/Predis/Commands/StringGetSet.php b/lib/Predis/Commands/StringGetSet.php index cba7a41a..5918aa71 100644 --- a/lib/Predis/Commands/StringGetSet.php +++ b/lib/Predis/Commands/StringGetSet.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringGetSet extends Command { - public function getId() { +class StringGetSet extends Command +{ + public function getId() + { return 'GETSET'; } } diff --git a/lib/Predis/Commands/StringIncrement.php b/lib/Predis/Commands/StringIncrement.php index cd7a2da3..0faf9072 100644 --- a/lib/Predis/Commands/StringIncrement.php +++ b/lib/Predis/Commands/StringIncrement.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringIncrement extends Command { - public function getId() { +class StringIncrement extends Command +{ + public function getId() + { return 'INCR'; } } diff --git a/lib/Predis/Commands/StringIncrementBy.php b/lib/Predis/Commands/StringIncrementBy.php index 65458c54..dce5f741 100644 --- a/lib/Predis/Commands/StringIncrementBy.php +++ b/lib/Predis/Commands/StringIncrementBy.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringIncrementBy extends Command { - public function getId() { +class StringIncrementBy extends Command +{ + public function getId() + { return 'INCRBY'; } } diff --git a/lib/Predis/Commands/StringSet.php b/lib/Predis/Commands/StringSet.php index 2ef9fb6e..d6afb2fc 100644 --- a/lib/Predis/Commands/StringSet.php +++ b/lib/Predis/Commands/StringSet.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringSet extends Command { - public function getId() { +class StringSet extends Command +{ + public function getId() + { return 'SET'; } } diff --git a/lib/Predis/Commands/StringSetBit.php b/lib/Predis/Commands/StringSetBit.php index 87d989a7..6e60c884 100644 --- a/lib/Predis/Commands/StringSetBit.php +++ b/lib/Predis/Commands/StringSetBit.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringSetBit extends Command { - public function getId() { +class StringSetBit extends Command +{ + public function getId() + { return 'SETBIT'; } } diff --git a/lib/Predis/Commands/StringSetExpire.php b/lib/Predis/Commands/StringSetExpire.php index 14ed8f95..723f565e 100644 --- a/lib/Predis/Commands/StringSetExpire.php +++ b/lib/Predis/Commands/StringSetExpire.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringSetExpire extends Command { - public function getId() { +class StringSetExpire extends Command +{ + public function getId() + { return 'SETEX'; } } diff --git a/lib/Predis/Commands/StringSetMultiple.php b/lib/Predis/Commands/StringSetMultiple.php index c5cb53ad..70ad4de0 100644 --- a/lib/Predis/Commands/StringSetMultiple.php +++ b/lib/Predis/Commands/StringSetMultiple.php @@ -2,38 +2,50 @@ namespace Predis\Commands; -class StringSetMultiple extends Command { - public function getId() { +class StringSetMultiple extends Command +{ + public function getId() + { return 'MSET'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (count($arguments) === 1 && is_array($arguments[0])) { $flattenedKVs = array(); $args = $arguments[0]; + foreach ($args as $k => $v) { $flattenedKVs[] = $k; $flattenedKVs[] = $v; } + return $flattenedKVs; } + return $arguments; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { $length = count($arguments); + for ($i = 0; $i < $length; $i += 2) { $arguments[$i] = "$prefix{$arguments[$i]}"; } + return $arguments; } - protected function canBeHashed() { + protected function canBeHashed() + { $args = $this->getArguments(); $keys = array(); + for ($i = 0; $i < count($args); $i += 2) { $keys[] = $args[$i]; } + return $this->checkSameHashForKeys($keys); } } diff --git a/lib/Predis/Commands/StringSetMultiplePreserve.php b/lib/Predis/Commands/StringSetMultiplePreserve.php index 0ec302c2..05ec926e 100644 --- a/lib/Predis/Commands/StringSetMultiplePreserve.php +++ b/lib/Predis/Commands/StringSetMultiplePreserve.php @@ -3,11 +3,13 @@ namespace Predis\Commands; class StringSetMultiplePreserve extends StringSetMultiple { - public function getId() { + public function getId() + { return 'MSETNX'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/StringSetPreserve.php b/lib/Predis/Commands/StringSetPreserve.php index 64a963d8..8cf6df76 100644 --- a/lib/Predis/Commands/StringSetPreserve.php +++ b/lib/Predis/Commands/StringSetPreserve.php @@ -3,11 +3,13 @@ namespace Predis\Commands; class StringSetPreserve extends Command { - public function getId() { + public function getId() + { return 'SETNX'; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/StringSetRange.php b/lib/Predis/Commands/StringSetRange.php index 85989941..81aec2d4 100644 --- a/lib/Predis/Commands/StringSetRange.php +++ b/lib/Predis/Commands/StringSetRange.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringSetRange extends Command { - public function getId() { +class StringSetRange extends Command +{ + public function getId() + { return 'SETRANGE'; } } diff --git a/lib/Predis/Commands/StringStrlen.php b/lib/Predis/Commands/StringStrlen.php index 3b3a4205..e72ea4db 100644 --- a/lib/Predis/Commands/StringStrlen.php +++ b/lib/Predis/Commands/StringStrlen.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringStrlen extends Command { - public function getId() { +class StringStrlen extends Command +{ + public function getId() + { return 'STRLEN'; } } diff --git a/lib/Predis/Commands/StringSubstr.php b/lib/Predis/Commands/StringSubstr.php index e11a434e..2f05e069 100644 --- a/lib/Predis/Commands/StringSubstr.php +++ b/lib/Predis/Commands/StringSubstr.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class StringSubstr extends Command { - public function getId() { +class StringSubstr extends Command +{ + public function getId() + { return 'SUBSTR'; } } diff --git a/lib/Predis/Commands/TransactionDiscard.php b/lib/Predis/Commands/TransactionDiscard.php index 47465149..6d8cab0d 100644 --- a/lib/Predis/Commands/TransactionDiscard.php +++ b/lib/Predis/Commands/TransactionDiscard.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class TransactionDiscard extends Command { - public function getId() { +class TransactionDiscard extends Command +{ + public function getId() + { return 'DISCARD'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/TransactionExec.php b/lib/Predis/Commands/TransactionExec.php index a9fbb0e7..2a750f90 100644 --- a/lib/Predis/Commands/TransactionExec.php +++ b/lib/Predis/Commands/TransactionExec.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class TransactionExec extends Command { - public function getId() { +class TransactionExec extends Command +{ + public function getId() + { return 'EXEC'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/TransactionMulti.php b/lib/Predis/Commands/TransactionMulti.php index c889b084..e66d6414 100644 --- a/lib/Predis/Commands/TransactionMulti.php +++ b/lib/Predis/Commands/TransactionMulti.php @@ -2,16 +2,20 @@ namespace Predis\Commands; -class TransactionMulti extends Command { - public function getId() { +class TransactionMulti extends Command +{ + public function getId() + { return 'MULTI'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } } diff --git a/lib/Predis/Commands/TransactionUnwatch.php b/lib/Predis/Commands/TransactionUnwatch.php index f031d899..5cd4a72b 100644 --- a/lib/Predis/Commands/TransactionUnwatch.php +++ b/lib/Predis/Commands/TransactionUnwatch.php @@ -2,20 +2,25 @@ namespace Predis\Commands; -class TransactionUnwatch extends Command { - public function getId() { +class TransactionUnwatch extends Command +{ + public function getId() + { return 'UNWATCH'; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { /* NOOP */ } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/TransactionWatch.php b/lib/Predis/Commands/TransactionWatch.php index d3cf3164..198332ad 100644 --- a/lib/Predis/Commands/TransactionWatch.php +++ b/lib/Predis/Commands/TransactionWatch.php @@ -2,27 +2,34 @@ namespace Predis\Commands; -class TransactionWatch extends Command { - public function getId() { +class TransactionWatch extends Command +{ + public function getId() + { return 'WATCH'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (isset($arguments[0]) && is_array($arguments[0])) { return $arguments[0]; } + return $arguments; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { return PrefixHelpers::multipleKeys($arguments, $prefix); } - protected function canBeHashed() { + protected function canBeHashed() + { return false; } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/ZSetAdd.php b/lib/Predis/Commands/ZSetAdd.php index bb0cf258..baba4fa5 100644 --- a/lib/Predis/Commands/ZSetAdd.php +++ b/lib/Predis/Commands/ZSetAdd.php @@ -4,16 +4,20 @@ namespace Predis\Commands; use Predis\Helpers; -class ZSetAdd extends Command { - public function getId() { +class ZSetAdd extends Command +{ + public function getId() + { return 'ZADD'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/ZSetCardinality.php b/lib/Predis/Commands/ZSetCardinality.php index 9b2f3524..4532afbe 100644 --- a/lib/Predis/Commands/ZSetCardinality.php +++ b/lib/Predis/Commands/ZSetCardinality.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetCardinality extends Command { - public function getId() { +class ZSetCardinality extends Command +{ + public function getId() + { return 'ZCARD'; } } diff --git a/lib/Predis/Commands/ZSetCount.php b/lib/Predis/Commands/ZSetCount.php index f7b581ce..2a581945 100644 --- a/lib/Predis/Commands/ZSetCount.php +++ b/lib/Predis/Commands/ZSetCount.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetCount extends Command { - public function getId() { +class ZSetCount extends Command +{ + public function getId() + { return 'ZCOUNT'; } } diff --git a/lib/Predis/Commands/ZSetIncrementBy.php b/lib/Predis/Commands/ZSetIncrementBy.php index dfa7e791..956b9410 100644 --- a/lib/Predis/Commands/ZSetIncrementBy.php +++ b/lib/Predis/Commands/ZSetIncrementBy.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetIncrementBy extends Command { - public function getId() { +class ZSetIncrementBy extends Command +{ + public function getId() + { return 'ZINCRBY'; } } diff --git a/lib/Predis/Commands/ZSetIntersectionStore.php b/lib/Predis/Commands/ZSetIntersectionStore.php index 98afd4db..876add5b 100644 --- a/lib/Predis/Commands/ZSetIntersectionStore.php +++ b/lib/Predis/Commands/ZSetIntersectionStore.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetIntersectionStore extends ZSetUnionStore { - public function getId() { +class ZSetIntersectionStore extends ZSetUnionStore +{ + public function getId() + { return 'ZINTERSTORE'; } } diff --git a/lib/Predis/Commands/ZSetRange.php b/lib/Predis/Commands/ZSetRange.php index 964e3839..c02939dd 100644 --- a/lib/Predis/Commands/ZSetRange.php +++ b/lib/Predis/Commands/ZSetRange.php @@ -4,55 +4,72 @@ namespace Predis\Commands; use Predis\Iterators\MultiBulkResponseTuple; -class ZSetRange extends Command { - public function getId() { +class ZSetRange extends Command +{ + public function getId() + { return 'ZRANGE'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { if (count($arguments) === 4) { $lastType = gettype($arguments[3]); + if ($lastType === 'string' && strtolower($arguments[3]) === 'withscores') { // Used for compatibility with older versions $arguments[3] = array('WITHSCORES' => true); $lastType = 'array'; } + if ($lastType === 'array') { $options = $this->prepareOptions(array_pop($arguments)); return array_merge($arguments, $options); } } + return $arguments; } - protected function prepareOptions($options) { + protected function prepareOptions($options) + { $opts = array_change_key_case($options, CASE_UPPER); $finalizedOpts = array(); + if (isset($opts['WITHSCORES'])) { $finalizedOpts[] = 'WITHSCORES'; } + return $finalizedOpts; } - protected function withScores() { + protected function withScores() + { $arguments = $this->getArguments(); + if (count($arguments) < 4) { return false; } + return strtoupper($arguments[3]) === 'WITHSCORES'; } - public function parseResponse($data) { + public function parseResponse($data) + { if ($this->withScores()) { if ($data instanceof \Iterator) { return new MultiBulkResponseTuple($data); } + $result = array(); + for ($i = 0; $i < count($data); $i++) { $result[] = array($data[$i], $data[++$i]); } + return $result; } + return $data; } } diff --git a/lib/Predis/Commands/ZSetRangeByScore.php b/lib/Predis/Commands/ZSetRangeByScore.php index a837df09..92e3853e 100644 --- a/lib/Predis/Commands/ZSetRangeByScore.php +++ b/lib/Predis/Commands/ZSetRangeByScore.php @@ -2,34 +2,44 @@ namespace Predis\Commands; -class ZSetRangeByScore extends ZSetRange { - public function getId() { +class ZSetRangeByScore extends ZSetRange +{ + public function getId() + { return 'ZRANGEBYSCORE'; } - protected function prepareOptions($options) { + protected function prepareOptions($options) + { $opts = array_change_key_case($options, CASE_UPPER); $finalizedOpts = array(); + if (isset($opts['LIMIT']) && is_array($opts['LIMIT'])) { $limit = array_change_key_case($opts['LIMIT'], CASE_UPPER); + $finalizedOpts[] = 'LIMIT'; $finalizedOpts[] = isset($limit['OFFSET']) ? $limit['OFFSET'] : $limit[0]; $finalizedOpts[] = isset($limit['COUNT']) ? $limit['COUNT'] : $limit[1]; } + return array_merge($finalizedOpts, parent::prepareOptions($options)); } - protected function withScores() { + protected function withScores() + { $arguments = $this->getArguments(); + for ($i = 3; $i < count($arguments); $i++) { switch (strtoupper($arguments[$i])) { case 'WITHSCORES': return true; + case 'LIMIT': $i += 2; break; } } + return false; } } diff --git a/lib/Predis/Commands/ZSetRank.php b/lib/Predis/Commands/ZSetRank.php index 813518ec..82b38972 100644 --- a/lib/Predis/Commands/ZSetRank.php +++ b/lib/Predis/Commands/ZSetRank.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetRank extends Command { - public function getId() { +class ZSetRank extends Command +{ + public function getId() + { return 'ZRANK'; } } diff --git a/lib/Predis/Commands/ZSetRemove.php b/lib/Predis/Commands/ZSetRemove.php index 238d9de3..2020ba96 100644 --- a/lib/Predis/Commands/ZSetRemove.php +++ b/lib/Predis/Commands/ZSetRemove.php @@ -4,16 +4,20 @@ namespace Predis\Commands; use Predis\Helpers; -class ZSetRemove extends Command { - public function getId() { +class ZSetRemove extends Command +{ + public function getId() + { return 'ZREM'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { return Helpers::filterVariadicValues($arguments); } - public function parseResponse($data) { + public function parseResponse($data) + { return (bool) $data; } } diff --git a/lib/Predis/Commands/ZSetRemoveRangeByRank.php b/lib/Predis/Commands/ZSetRemoveRangeByRank.php index 8f17a111..e62417bf 100644 --- a/lib/Predis/Commands/ZSetRemoveRangeByRank.php +++ b/lib/Predis/Commands/ZSetRemoveRangeByRank.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetRemoveRangeByRank extends Command { - public function getId() { +class ZSetRemoveRangeByRank extends Command +{ + public function getId() + { return 'ZREMRANGEBYRANK'; } } diff --git a/lib/Predis/Commands/ZSetRemoveRangeByScore.php b/lib/Predis/Commands/ZSetRemoveRangeByScore.php index b589c9f3..2db18d8e 100644 --- a/lib/Predis/Commands/ZSetRemoveRangeByScore.php +++ b/lib/Predis/Commands/ZSetRemoveRangeByScore.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetRemoveRangeByScore extends Command { - public function getId() { +class ZSetRemoveRangeByScore extends Command +{ + public function getId() + { return 'ZREMRANGEBYSCORE'; } } diff --git a/lib/Predis/Commands/ZSetReverseRange.php b/lib/Predis/Commands/ZSetReverseRange.php index 588ce192..f1cc0ab1 100644 --- a/lib/Predis/Commands/ZSetReverseRange.php +++ b/lib/Predis/Commands/ZSetReverseRange.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetReverseRange extends ZSetRange { - public function getId() { +class ZSetReverseRange extends ZSetRange +{ + public function getId() + { return 'ZREVRANGE'; } } diff --git a/lib/Predis/Commands/ZSetReverseRangeByScore.php b/lib/Predis/Commands/ZSetReverseRangeByScore.php index bc3ebdc1..4fa2796e 100644 --- a/lib/Predis/Commands/ZSetReverseRangeByScore.php +++ b/lib/Predis/Commands/ZSetReverseRangeByScore.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetReverseRangeByScore extends ZSetRangeByScore { - public function getId() { +class ZSetReverseRangeByScore extends ZSetRangeByScore +{ + public function getId() + { return 'ZREVRANGEBYSCORE'; } } diff --git a/lib/Predis/Commands/ZSetReverseRank.php b/lib/Predis/Commands/ZSetReverseRank.php index 603bbf1e..60a822e1 100644 --- a/lib/Predis/Commands/ZSetReverseRank.php +++ b/lib/Predis/Commands/ZSetReverseRank.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetReverseRank extends Command { - public function getId() { +class ZSetReverseRank extends Command +{ + public function getId() + { return 'ZREVRANK'; } } diff --git a/lib/Predis/Commands/ZSetScore.php b/lib/Predis/Commands/ZSetScore.php index 7bbda282..7f4039e3 100644 --- a/lib/Predis/Commands/ZSetScore.php +++ b/lib/Predis/Commands/ZSetScore.php @@ -2,8 +2,10 @@ namespace Predis\Commands; -class ZSetScore extends Command { - public function getId() { +class ZSetScore extends Command +{ + public function getId() + { return 'ZSCORE'; } } diff --git a/lib/Predis/Commands/ZSetUnionStore.php b/lib/Predis/Commands/ZSetUnionStore.php index 8fa45ab7..fe9fd6a4 100644 --- a/lib/Predis/Commands/ZSetUnionStore.php +++ b/lib/Predis/Commands/ZSetUnionStore.php @@ -2,53 +2,68 @@ namespace Predis\Commands; -class ZSetUnionStore extends Command { - public function getId() { +class ZSetUnionStore extends Command +{ + public function getId() + { return 'ZUNIONSTORE'; } - protected function filterArguments(Array $arguments) { + protected function filterArguments(Array $arguments) + { $options = array(); $argc = count($arguments); + if ($argc > 2 && is_array($arguments[$argc - 1])) { $options = $this->prepareOptions(array_pop($arguments)); } + if (is_array($arguments[1])) { $arguments = array_merge( array($arguments[0], count($arguments[1])), $arguments[1] ); } + return array_merge($arguments, $options); } - private function prepareOptions($options) { + private function prepareOptions($options) + { $opts = array_change_key_case($options, CASE_UPPER); $finalizedOpts = array(); + if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) { $finalizedOpts[] = 'WEIGHTS'; foreach ($opts['WEIGHTS'] as $weight) { $finalizedOpts[] = $weight; } } + if (isset($opts['AGGREGATE'])) { $finalizedOpts[] = 'AGGREGATE'; $finalizedOpts[] = $opts['AGGREGATE']; } + return $finalizedOpts; } - protected function onPrefixKeys(Array $arguments, $prefix) { + protected function onPrefixKeys(Array $arguments, $prefix) + { $arguments[0] = "$prefix{$arguments[0]}"; $length = ((int) $arguments[1]) + 2; + for ($i = 2; $i < $length; $i++) { $arguments[$i] = "$prefix{$arguments[$i]}"; } + return $arguments; } - protected function canBeHashed() { + protected function canBeHashed() + { $args = $this->getArguments(); + return $this->checkSameHashForKeys( array_merge(array($args[0]), array_slice($args, 2, $args[1])) ); diff --git a/lib/Predis/CommunicationException.php b/lib/Predis/CommunicationException.php index 9e1a183b..b41ab298 100644 --- a/lib/Predis/CommunicationException.php +++ b/lib/Predis/CommunicationException.php @@ -4,21 +4,24 @@ namespace Predis; use Predis\Network\IConnectionSingle; -abstract class CommunicationException extends PredisException { +abstract class CommunicationException extends PredisException +{ private $_connection; - public function __construct(IConnectionSingle $connection, $message = null, - $code = null, \Exception $innerException = null) { + public function __construct(IConnectionSingle $connection, $message = null, $code = null, \Exception $innerException = null) + { + parent::__construct($message, $code, $innerException); $this->_connection = $connection; - parent::__construct($message, $code, $innerException); } - public function getConnection() { + public function getConnection() + { return $this->_connection; } - public function shouldResetConnection() { + public function shouldResetConnection() + { return true; } } diff --git a/lib/Predis/ConnectionFactory.php b/lib/Predis/ConnectionFactory.php index 98f2997f..e0daff3a 100644 --- a/lib/Predis/ConnectionFactory.php +++ b/lib/Predis/ConnectionFactory.php @@ -4,12 +4,16 @@ namespace Predis; use Predis\Network\IConnectionSingle; -class ConnectionFactory implements IConnectionFactory { +class ConnectionFactory implements IConnectionFactory +{ private static $_globalSchemes; + private $_instanceSchemes = array(); - public function __construct(Array $schemesMap = null) { + public function __construct(Array $schemesMap = null) + { $this->_instanceSchemes = self::ensureDefaultSchemes(); + if (isset($schemesMap)) { foreach ($schemesMap as $scheme => $initializer) { $this->defineConnection($scheme, $initializer); @@ -17,11 +21,14 @@ class ConnectionFactory implements IConnectionFactory { } } - private static function checkConnectionInitializer($initializer) { + private static function checkConnectionInitializer($initializer) + { if (is_callable($initializer)) { return; } + $initializerReflection = new \ReflectionClass($initializer); + if (!$initializerReflection->isSubclassOf('\Predis\Network\IConnectionSingle')) { throw new \InvalidArgumentException( 'A connection initializer must be a valid connection class or a callable object' @@ -29,28 +36,33 @@ class ConnectionFactory implements IConnectionFactory { } } - private static function ensureDefaultSchemes() { + private static function ensureDefaultSchemes() + { if (!isset(self::$_globalSchemes)) { self::$_globalSchemes = array( 'tcp' => '\Predis\Network\StreamConnection', 'unix' => '\Predis\Network\StreamConnection', ); } + return self::$_globalSchemes; } - public static function define($scheme, $connectionInitializer) { + public static function define($scheme, $connectionInitializer) + { self::ensureDefaultSchemes(); self::checkConnectionInitializer($connectionInitializer); self::$_globalSchemes[$scheme] = $connectionInitializer; } - public function defineConnection($scheme, $connectionInitializer) { + public function defineConnection($scheme, $connectionInitializer) + { self::checkConnectionInitializer($connectionInitializer); $this->_instanceSchemes[$scheme] = $connectionInitializer; } - public function create($parameters) { + public function create($parameters) + { if (!$parameters instanceof IConnectionParameters) { $parameters = new ConnectionParameters($parameters); } @@ -66,14 +78,13 @@ class ConnectionFactory implements IConnectionFactory { } $connection = call_user_func($initializer, $parameters); - if ($connection instanceof IConnectionSingle) { - return $connection; - } - else { + if (!$connection instanceof IConnectionSingle) { throw new \InvalidArgumentException( 'Objects returned by connection initializers must implement ' . 'the Predis\Network\IConnectionSingle interface' ); } + + return $connection; } } diff --git a/lib/Predis/ConnectionParameters.php b/lib/Predis/ConnectionParameters.php index 6053ff7d..e1165df0 100644 --- a/lib/Predis/ConnectionParameters.php +++ b/lib/Predis/ConnectionParameters.php @@ -5,23 +5,28 @@ namespace Predis; use Predis\IConnectionParameters; use Predis\Options\IOption; -class ConnectionParameters implements IConnectionParameters { +class ConnectionParameters implements IConnectionParameters +{ private static $_defaultParameters; private static $_validators; private $_parameters; private $_userDefined; - public function __construct($parameters = array()) { + public function __construct($parameters = array()) + { self::ensureDefaults(); + if (!is_array($parameters)) { $parameters = $this->parseURI($parameters); } + $this->_userDefined = array_keys($parameters); $this->_parameters = $this->filter($parameters) + self::$_defaultParameters; } - private static function ensureDefaults() { + private static function ensureDefaults() + { if (!isset(self::$_defaultParameters)) { self::$_defaultParameters = array( 'scheme' => 'tcp', @@ -40,55 +45,65 @@ class ConnectionParameters implements IConnectionParameters { 'throw_errors' => true, ); } + if (!isset(self::$_validators)) { - $boolValidator = function($value) { return (bool) $value; }; - $floatValidator = function($value) { return (float) $value; }; - $intValidator = function($value) { return (int) $value; }; + $bool = function($value) { return (bool) $value; }; + $float = function($value) { return (float) $value; }; + $int = function($value) { return (int) $value; }; self::$_validators = array( - 'port' => $intValidator, - 'connection_async' => $boolValidator, - 'connection_persistent' => $boolValidator, - 'connection_timeout' => $floatValidator, - 'read_write_timeout' => $floatValidator, - 'iterable_multibulk' => $boolValidator, - 'throw_errors' => $boolValidator, + 'port' => $int, + 'connection_async' => $bool, + 'connection_persistent' => $bool, + 'connection_timeout' => $float, + 'read_write_timeout' => $float, + 'iterable_multibulk' => $bool, + 'throw_errors' => $bool, ); } } - public static function define($parameter, $default, $callable = null) { + public static function define($parameter, $default, $callable = null) + { self::ensureDefaults(); self::$_defaultParameters[$parameter] = $default; + if ($default instanceof IOption) { self::$_validators[$parameter] = $default; return; } + if (!isset($callable)) { unset(self::$_validators[$parameter]); return; } + if (!is_callable($callable)) { throw new \InvalidArgumentException( "The validator for $parameter must be a callable object" ); } + self::$_validators[$parameter] = $callable; } - public static function undefine($parameter) { + public static function undefine($parameter) + { self::ensureDefaults(); unset(self::$_defaultParameters[$parameter], self::$_validators[$parameter]); } - private function parseURI($uri) { + private function parseURI($uri) + { if (stripos($uri, 'unix') === 0) { // Hack to support URIs for UNIX sockets with minimal effort. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri); } + if (($parsed = @parse_url($uri)) === false || !isset($parsed['host'])) { throw new ClientException("Invalid URI: $uri"); } + if (isset($parsed['query'])) { foreach (explode('&', $parsed['query']) as $kv) { @list($k, $v) = explode('=', $kv); @@ -96,54 +111,68 @@ class ConnectionParameters implements IConnectionParameters { } unset($parsed['query']); } + return $parsed; } - private function filter(Array $parameters) { + private function filter(Array $parameters) + { if (count($parameters) > 0) { $validators = array_intersect_key(self::$_validators, $parameters); foreach ($validators as $parameter => $validator) { $parameters[$parameter] = $validator($parameters[$parameter]); } } + return $parameters; } - public function __get($parameter) { + public function __get($parameter) + { $value = $this->_parameters[$parameter]; + if ($value instanceof IOption) { $this->_parameters[$parameter] = ($value = $value->getDefault()); } + return $value; } - public function __isset($parameter) { + public function __isset($parameter) + { return isset($this->_parameters[$parameter]); } - public function isSetByUser($parameter) { + public function isSetByUser($parameter) + { return in_array($parameter, $this->_userDefined); } - protected function getBaseURI() { + protected function getBaseURI() + { if ($this->scheme === 'unix') { return "{$this->scheme}://{$this->path}"; } + return "{$this->scheme}://{$this->host}:{$this->port}"; } - protected function getDisallowedURIParts() { + protected function getDisallowedURIParts() + { return array('scheme', 'host', 'port', 'password', 'path'); } - public function toArray() { + public function toArray() + { return $this->_parameters; } - public function __toString() { + public function __toString() + { $query = array(); $parameters = $this->toArray(); $reject = $this->getDisallowedURIParts(); + foreach ($this->_userDefined as $param) { if (in_array($param, $reject) || !isset($parameters[$param])) { continue; @@ -151,17 +180,21 @@ class ConnectionParameters implements IConnectionParameters { $value = $parameters[$param]; $query[] = "$param=" . ($value === false ? '0' : $value); } + if (count($query) === 0) { return $this->getBaseURI(); } + return $this->getBaseURI() . '/?' . implode('&', $query); } - public function __sleep() { + public function __sleep() + { return array('_parameters', '_userDefined'); } - public function __wakeup() { + public function __wakeup() + { self::ensureDefaults(); } } diff --git a/lib/Predis/DispatcherLoop.php b/lib/Predis/DispatcherLoop.php index 3ec06513..f40d7c79 100644 --- a/lib/Predis/DispatcherLoop.php +++ b/lib/Predis/DispatcherLoop.php @@ -2,20 +2,23 @@ namespace Predis; -class DispatcherLoop { +class DispatcherLoop +{ private $_client; private $_pubSubContext; private $_callbacks; private $_defaultCallback; private $_subscriptionCallback; - public function __construct(Client $client) { + public function __construct(Client $client) + { $this->_callbacks = array(); $this->_client = $client; $this->_pubSubContext = $client->pubSub(); } - protected function validateCallback($callback) { + protected function validateCallback($callback) + { if (!is_callable($callback)) { throw new ClientException( "The callback parameter must be a valid callable object" @@ -23,40 +26,47 @@ class DispatcherLoop { } } - public function getPubSubContext() { + public function getPubSubContext() + { return $this->_pubSubContext; } - public function subscriptionCallback($callback = null) { + public function subscriptionCallback($callback = null) + { if (isset($callback)) { $this->validateCallback($callback); } $this->_subscriptionCallback = $callback; } - public function defaultCallback($callback = null) { + public function defaultCallback($callback = null) + { if (isset($callback)) { $this->validateCallback($callback); } $this->_subscriptionCallback = $callback; } - public function attachCallback($channel, $callback) { + public function attachCallback($channel, $callback) + { $this->validateCallback($callback); $this->_callbacks[$channel] = $callback; $this->_pubSubContext->subscribe($channel); } - public function detachCallback($channel) { + public function detachCallback($channel) + { if (isset($this->_callbacks[$channel])) { unset($this->_callbacks[$channel]); $this->_pubSubContext->unsubscribe($channel); } } - public function run() { + public function run() + { foreach ($this->_pubSubContext as $message) { $kind = $message->kind; + if ($kind !== PubSubContext::MESSAGE && $kind !== PubSubContext::PMESSAGE) { if (isset($this->_subscriptionCallback)) { $callback = $this->_subscriptionCallback; @@ -64,6 +74,7 @@ class DispatcherLoop { } continue; } + if (isset($this->_callbacks[$message->channel])) { $callback = $this->_callbacks[$message->channel]; $callback($message->payload); @@ -75,7 +86,8 @@ class DispatcherLoop { } } - public function stop() { + public function stop() + { $this->_pubSubContext->closeContext(); } } diff --git a/lib/Predis/Distribution/EmptyRingException.php b/lib/Predis/Distribution/EmptyRingException.php index 663035d9..873c02f8 100644 --- a/lib/Predis/Distribution/EmptyRingException.php +++ b/lib/Predis/Distribution/EmptyRingException.php @@ -2,5 +2,6 @@ namespace Predis\Distribution; -class EmptyRingException extends \Exception { +class EmptyRingException extends \Exception +{ } diff --git a/lib/Predis/Distribution/HashRing.php b/lib/Predis/Distribution/HashRing.php index 53e0099e..dc14d50a 100644 --- a/lib/Predis/Distribution/HashRing.php +++ b/lib/Predis/Distribution/HashRing.php @@ -2,7 +2,8 @@ namespace Predis\Distribution; -class HashRing implements IDistributionStrategy { +class HashRing implements IDistributionStrategy +{ const DEFAULT_REPLICAS = 128; const DEFAULT_WEIGHT = 100; @@ -12,19 +13,22 @@ class HashRing implements IDistributionStrategy { private $_ringKeysCount; private $_replicas; - public function __construct($replicas = self::DEFAULT_REPLICAS) { + public function __construct($replicas = self::DEFAULT_REPLICAS) + { $this->_replicas = $replicas; $this->_nodes = array(); } - public function add($node, $weight = null) { + public function add($node, $weight = null) + { // In case of collisions in the hashes of the nodes, the node added // last wins, thus the order in which nodes are added is significant. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT); $this->reset(); } - public function remove($node) { + public function remove($node) + { // A node is removed by resetting the ring so that it's recreated from // scratch, in order to reassign possible hashes with collisions to the // right node according to the order in which they were added in the @@ -38,7 +42,8 @@ class HashRing implements IDistributionStrategy { } } - private function reset() { + private function reset() + { unset( $this->_ring, $this->_ringKeys, @@ -46,22 +51,27 @@ class HashRing implements IDistributionStrategy { ); } - private function isInitialized() { + private function isInitialized() + { return isset($this->_ringKeys); } - private function computeTotalWeight() { + private function computeTotalWeight() + { $totalWeight = 0; foreach ($this->_nodes as $node) { $totalWeight += $node['weight']; } + return $totalWeight; } - private function initialize() { + private function initialize() + { if ($this->isInitialized()) { return; } + if (count($this->_nodes) === 0) { throw new EmptyRingException('Cannot initialize empty hashring'); } @@ -69,38 +79,46 @@ class HashRing implements IDistributionStrategy { $this->_ring = array(); $totalWeight = $this->computeTotalWeight(); $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); + $this->_ringKeys = array_keys($this->_ring); $this->_ringKeysCount = count($this->_ringKeys); } - protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { + protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) + { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) round($weightRatio * $totalNodes * $replicas); + for ($i = 0; $i < $replicas; $i++) { $key = crc32("$nodeHash:$i"); $ring[$key] = $nodeObject; } } - protected function getNodeHash($nodeObject) { + protected function getNodeHash($nodeObject) + { return (string) $nodeObject; } - public function generateKey($value) { + public function generateKey($value) + { return crc32($value); } - public function get($key) { + public function get($key) + { return $this->_ring[$this->getNodeKey($key)]; } - private function getNodeKey($key) { + private function getNodeKey($key) + { $this->initialize(); $ringKeys = $this->_ringKeys; $upper = $this->_ringKeysCount - 1; @@ -119,10 +137,12 @@ class HashRing implements IDistributionStrategy { return $item; } } + return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)]; } - protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) { + protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) + { // Binary search for the last item in _ringkeys with a value less or // equal to the key. If no such item exists, return the last item. return $upper >= 0 ? $upper : $ringKeysCount - 1; diff --git a/lib/Predis/Distribution/IDistributionStrategy.php b/lib/Predis/Distribution/IDistributionStrategy.php index 7f398625..b847b7b7 100644 --- a/lib/Predis/Distribution/IDistributionStrategy.php +++ b/lib/Predis/Distribution/IDistributionStrategy.php @@ -2,7 +2,8 @@ namespace Predis\Distribution; -interface IDistributionStrategy extends INodeKeyGenerator { +interface IDistributionStrategy extends INodeKeyGenerator +{ public function add($node, $weight = null); public function remove($node); public function get($key); diff --git a/lib/Predis/Distribution/INodeKeyGenerator.php b/lib/Predis/Distribution/INodeKeyGenerator.php index 328356ec..7af5c676 100644 --- a/lib/Predis/Distribution/INodeKeyGenerator.php +++ b/lib/Predis/Distribution/INodeKeyGenerator.php @@ -2,6 +2,7 @@ namespace Predis\Distribution; -interface INodeKeyGenerator { +interface INodeKeyGenerator +{ public function generateKey($value); } diff --git a/lib/Predis/Distribution/KetamaPureRing.php b/lib/Predis/Distribution/KetamaPureRing.php index 5439531d..056b89d2 100644 --- a/lib/Predis/Distribution/KetamaPureRing.php +++ b/lib/Predis/Distribution/KetamaPureRing.php @@ -2,17 +2,21 @@ namespace Predis\Distribution; -class KetamaPureRing extends HashRing { +class KetamaPureRing extends HashRing +{ const DEFAULT_REPLICAS = 160; - public function __construct() { + public function __construct() + { parent::__construct($this::DEFAULT_REPLICAS); } - protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { + protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) + { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4)); + for ($i = 0; $i < $replicas; $i++) { $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true)); foreach ($unpackedDigest as $key) { @@ -21,12 +25,14 @@ class KetamaPureRing extends HashRing { } } - public function generateKey($value) { + public function generateKey($value) + { $hash = unpack('V', md5($value, true)); return $hash[1]; } - protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) { + protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) + { // Binary search for the first item in _ringkeys with a value greater // or equal to the key. If no such item exists, return the first item. return $lower < $ringKeysCount ? $lower : 0; diff --git a/lib/Predis/Helpers.php b/lib/Predis/Helpers.php index 240b6384..403af5ad 100644 --- a/lib/Predis/Helpers.php +++ b/lib/Predis/Helpers.php @@ -5,36 +5,45 @@ namespace Predis; use Predis\Network\IConnection; use Predis\Network\IConnectionCluster; -class Helpers { - public static function isCluster(IConnection $connection) { +class Helpers +{ + public static function isCluster(IConnection $connection) + { return $connection instanceof IConnectionCluster; } - public static function onCommunicationException(CommunicationException $exception) { + public static function onCommunicationException(CommunicationException $exception) + { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } + throw $exception; } - public static function filterArrayArguments(Array $arguments) { + public static function filterArrayArguments(Array $arguments) + { if (count($arguments) === 1 && is_array($arguments[0])) { return $arguments[0]; } + return $arguments; } - public static function filterVariadicValues(Array $arguments) { + public static function filterVariadicValues(Array $arguments) + { if (count($arguments) === 2 && is_array($arguments[1])) { return array_merge(array($arguments[0]), $arguments[1]); } + return $arguments; } - public static function getKeyHashablePart($key) { + public static function getKeyHashablePart($key) + { $start = strpos($key, '{'); if ($start !== false) { $end = strpos($key, '}', $start); @@ -42,6 +51,7 @@ class Helpers { $key = substr($key, ++$start, $end - $start); } } + return $key; } } diff --git a/lib/Predis/IConnectionFactory.php b/lib/Predis/IConnectionFactory.php index 6a0bc154..4bc63912 100644 --- a/lib/Predis/IConnectionFactory.php +++ b/lib/Predis/IConnectionFactory.php @@ -2,6 +2,7 @@ namespace Predis; -interface IConnectionFactory { +interface IConnectionFactory +{ public function create($parameters); } diff --git a/lib/Predis/IConnectionParameters.php b/lib/Predis/IConnectionParameters.php index 891a79a8..d3db5699 100644 --- a/lib/Predis/IConnectionParameters.php +++ b/lib/Predis/IConnectionParameters.php @@ -2,7 +2,8 @@ namespace Predis; -interface IConnectionParameters { +interface IConnectionParameters +{ public function __isset($parameter); public function __get($parameter); public function toArray(); diff --git a/lib/Predis/IRedisServerError.php b/lib/Predis/IRedisServerError.php index cdf4a7f0..63f8aee9 100644 --- a/lib/Predis/IRedisServerError.php +++ b/lib/Predis/IRedisServerError.php @@ -2,7 +2,8 @@ namespace Predis; -interface IRedisServerError extends IReplyObject { +interface IRedisServerError extends IReplyObject +{ public function getMessage(); public function getErrorType(); } diff --git a/lib/Predis/IReplyObject.php b/lib/Predis/IReplyObject.php index fbcd1be6..ca6666dc 100644 --- a/lib/Predis/IReplyObject.php +++ b/lib/Predis/IReplyObject.php @@ -2,5 +2,6 @@ namespace Predis; -interface IReplyObject { +interface IReplyObject +{ } diff --git a/lib/Predis/Iterators/MultiBulkResponse.php b/lib/Predis/Iterators/MultiBulkResponse.php index ab49c0b5..277244d2 100644 --- a/lib/Predis/Iterators/MultiBulkResponse.php +++ b/lib/Predis/Iterators/MultiBulkResponse.php @@ -2,35 +2,43 @@ namespace Predis\Iterators; -abstract class MultiBulkResponse implements \Iterator, \Countable { +abstract class MultiBulkResponse implements \Iterator, \Countable +{ protected $_position; protected $_current; protected $_replySize; - public function rewind() { + public function rewind() + { // NOOP } - public function current() { + public function current() + { return $this->_current; } - public function key() { + public function key() + { return $this->_position; } - public function next() { + public function next() + { if (++$this->_position < $this->_replySize) { $this->_current = $this->getValue(); } + return $this->_position; } - public function valid() { + public function valid() + { return $this->_position < $this->_replySize; } - public function count() { + public function count() + { // Use count if you want to get the size of the current multi-bulk // response without using iterator_count (which actually consumes our // iterator to calculate the size, and we cannot perform a rewind) diff --git a/lib/Predis/Iterators/MultiBulkResponseSimple.php b/lib/Predis/Iterators/MultiBulkResponseSimple.php index 66b36391..9b04f878 100644 --- a/lib/Predis/Iterators/MultiBulkResponseSimple.php +++ b/lib/Predis/Iterators/MultiBulkResponseSimple.php @@ -5,17 +5,20 @@ namespace Predis\Iterators; use Predis\Network\IConnection; use Predis\Network\IConnectionSingle; -class MultiBulkResponseSimple extends MultiBulkResponse { +class MultiBulkResponseSimple extends MultiBulkResponse +{ private $_connection; - public function __construct(IConnectionSingle $connection, $size) { + public function __construct(IConnectionSingle $connection, $size) + { $this->_connection = $connection; $this->_position = 0; $this->_current = $size > 0 ? $this->getValue() : null; $this->_replySize = $size; } - public function __destruct() { + public function __destruct() + { // When the iterator is garbage-collected (e.g. it goes out of the // scope of a foreach) but it has not reached its end, we must sync // the client with the queued elements that have not been read from @@ -23,7 +26,8 @@ class MultiBulkResponseSimple extends MultiBulkResponse { $this->sync(); } - public function sync($drop = false) { + public function sync($drop = false) + { if ($drop == true) { if ($this->valid()) { $this->_position = $this->_replySize; @@ -37,7 +41,8 @@ class MultiBulkResponseSimple extends MultiBulkResponse { } } - protected function getValue() { + protected function getValue() + { return $this->_connection->read(); } } diff --git a/lib/Predis/Iterators/MultiBulkResponseTuple.php b/lib/Predis/Iterators/MultiBulkResponseTuple.php index df4a9879..110628c5 100644 --- a/lib/Predis/Iterators/MultiBulkResponseTuple.php +++ b/lib/Predis/Iterators/MultiBulkResponseTuple.php @@ -2,26 +2,32 @@ namespace Predis\Iterators; -class MultiBulkResponseTuple extends MultiBulkResponse { +class MultiBulkResponseTuple extends MultiBulkResponse +{ private $_iterator; - public function __construct(MultiBulkResponseSimple $iterator) { + public function __construct(MultiBulkResponseSimple $iterator) + { $virtualSize = count($iterator) / 2; - $this->_iterator = $iterator; - $this->_position = 0; - $this->_current = $virtualSize > 0 ? $this->getValue() : null; - $this->_replySize = $virtualSize; + $this->_iterator = $iterator; + $this->_position = 0; + $this->_current = $virtualSize > 0 ? $this->getValue() : null; + $this->_replySize = $virtualSize; } - public function __destruct() { + public function __destruct() + { $this->_iterator->sync(); } - protected function getValue() { + protected function getValue() + { $k = $this->_iterator->current(); $this->_iterator->next(); + $v = $this->_iterator->current(); $this->_iterator->next(); + return array($k, $v); } } diff --git a/lib/Predis/MonitorContext.php b/lib/Predis/MonitorContext.php index 75d2d0dc..9562ac34 100644 --- a/lib/Predis/MonitorContext.php +++ b/lib/Predis/MonitorContext.php @@ -2,27 +2,32 @@ namespace Predis; -class MonitorContext implements \Iterator { +class MonitorContext implements \Iterator +{ private $_client; private $_isValid; private $_position; - public function __construct(Client $client) { + public function __construct(Client $client) + { $this->checkCapabilities($client); $this->_client = $client; $this->openContext(); } - public function __destruct() { + public function __destruct() + { $this->closeContext(); } - private function checkCapabilities(Client $client) { + private function checkCapabilities(Client $client) + { if (Helpers::isCluster($client->getConnection())) { throw new ClientException( 'Cannot initialize a monitor context over a cluster of connections' ); } + if ($client->getProfile()->supportsCommand('monitor') === false) { throw new ClientException( 'The current profile does not support the MONITOR command' @@ -30,38 +35,46 @@ class MonitorContext implements \Iterator { } } - protected function openContext() { + protected function openContext() + { $this->_isValid = true; $monitor = $this->_client->createCommand('monitor'); $this->_client->executeCommand($monitor); } - public function closeContext() { + public function closeContext() + { $this->_client->disconnect(); $this->_isValid = false; } - public function rewind() { + public function rewind() + { // NOOP } - public function current() { + public function current() + { return $this->getValue(); } - public function key() { + public function key() + { return $this->_position; } - public function next() { + public function next() + { $this->_position++; } - public function valid() { + public function valid() + { return $this->_isValid; } - private function getValue() { + private function getValue() + { $database = 0; $event = $this->_client->getConnection()->read(); @@ -71,9 +84,10 @@ class MonitorContext implements \Iterator { } return ' '; }; - $event = preg_replace_callback('/ \(db (\d+)\) /', $callback, $event, 1); + $event = preg_replace_callback('/ \(db (\d+)\) /', $callback, $event, 1); @list($timestamp, $command, $arguments) = split(' ', $event, 3); + return (object) array( 'timestamp' => (float) $timestamp, 'database' => $database, diff --git a/lib/Predis/Network/ComposableStreamConnection.php b/lib/Predis/Network/ComposableStreamConnection.php index 63c8353a..ff756673 100644 --- a/lib/Predis/Network/ComposableStreamConnection.php +++ b/lib/Predis/Network/ComposableStreamConnection.php @@ -7,40 +7,50 @@ use Predis\Commands\ICommand; use Predis\Protocol\IProtocolProcessor; use Predis\Protocol\Text\TextProtocol; -class ComposableStreamConnection extends StreamConnection implements IConnectionComposable { +class ComposableStreamConnection extends StreamConnection implements IConnectionComposable +{ private $_protocol; - public function __construct(IConnectionParameters $parameters, IProtocolProcessor $protocol = null) { + public function __construct(IConnectionParameters $parameters, IProtocolProcessor $protocol = null) + { $this->setProtocol($protocol ?: new TextProtocol()); + parent::__construct($parameters); } - protected function initializeProtocol(IConnectionParameters $parameters) { + protected function initializeProtocol(IConnectionParameters $parameters) + { $this->_protocol->setOption('throw_errors', $parameters->throw_errors); $this->_protocol->setOption('iterable_multibulk', $parameters->iterable_multibulk); } - public function setProtocol(IProtocolProcessor $protocol) { + public function setProtocol(IProtocolProcessor $protocol) + { if ($protocol === null) { throw new \InvalidArgumentException("The protocol instance cannot be a null value"); } $this->_protocol = $protocol; } - public function getProtocol() { + public function getProtocol() + { return $this->_protocol; } - public function writeBytes($buffer) { + public function writeBytes($buffer) + { parent::writeBytes($buffer); } - public function readBytes($length) { + public function readBytes($length) + { if ($length <= 0) { throw new \InvalidArgumentException('Length parameter must be greater than 0'); } - $socket = $this->getResource(); + $value = ''; + $socket = $this->getResource(); + do { $chunk = fread($socket, $length); if ($chunk === false || $chunk === '') { @@ -49,12 +59,15 @@ class ComposableStreamConnection extends StreamConnection implements IConnection $value .= $chunk; } while (($length -= strlen($chunk)) > 0); + return $value; } - public function readLine() { - $socket = $this->getResource(); + public function readLine() + { $value = ''; + $socket = $this->getResource(); + do { $chunk = fgets($socket); if ($chunk === false || $chunk === '') { @@ -63,14 +76,17 @@ class ComposableStreamConnection extends StreamConnection implements IConnection $value .= $chunk; } while (substr($value, -2) !== "\r\n"); + return substr($value, 0, -2); } - public function writeCommand(ICommand $command) { + public function writeCommand(ICommand $command) + { $this->_protocol->write($this, $command); } - public function read() { + public function read() + { return $this->_protocol->read($this); } } diff --git a/lib/Predis/Network/ConnectionBase.php b/lib/Predis/Network/ConnectionBase.php index 50bccc46..7bf08c03 100644 --- a/lib/Predis/Network/ConnectionBase.php +++ b/lib/Predis/Network/ConnectionBase.php @@ -10,116 +10,140 @@ use Predis\ClientException; use Predis\Commands\ICommand; use Predis\Protocol\ProtocolException; -abstract class ConnectionBase implements IConnectionSingle { +abstract class ConnectionBase implements IConnectionSingle +{ private $_resource; private $_cachedId; + protected $_params; protected $_initCmds; - public function __construct(IConnectionParameters $parameters) { + public function __construct(IConnectionParameters $parameters) + { $this->_initCmds = array(); $this->_params = $this->checkParameters($parameters); $this->initializeProtocol($parameters); } - public function __destruct() { + public function __destruct() + { $this->disconnect(); } - protected function checkParameters(IConnectionParameters $parameters) { + protected function checkParameters(IConnectionParameters $parameters) + { switch ($parameters->scheme) { case 'unix': if (!isset($parameters->path)) { throw new InvalidArgumentException('Missing UNIX domain socket path'); } + case 'tcp': return $parameters; + default: throw new InvalidArgumentException("Invalid scheme: {$parameters->scheme}"); } } - protected function initializeProtocol(IConnectionParameters $parameters) { + protected function initializeProtocol(IConnectionParameters $parameters) + { // NOOP } protected abstract function createResource(); - public function isConnected() { + public function isConnected() + { return isset($this->_resource); } - public function connect() { + public function connect() + { if ($this->isConnected()) { throw new ClientException('Connection already estabilished'); } $this->_resource = $this->createResource(); } - public function disconnect() { + public function disconnect() + { unset($this->_resource); } - public function pushInitCommand(ICommand $command) { + public function pushInitCommand(ICommand $command) + { $this->_initCmds[] = $command; } - public function executeCommand(ICommand $command) { + public function executeCommand(ICommand $command) + { $this->writeCommand($command); return $this->readResponse($command); } - public function readResponse(ICommand $command) { + public function readResponse(ICommand $command) + { $reply = $this->read(); + if ($reply instanceof IReplyObject) { return $reply; } + return $command->parseResponse($reply); } - protected function onConnectionError($message, $code = null) { - Helpers::onCommunicationException( - new ConnectionException($this, $message, $code) - ); + protected function onConnectionError($message, $code = null) + { + Helpers::onCommunicationException(new ConnectionException($this, $message, $code)); } - protected function onProtocolError($message) { - Helpers::onCommunicationException( - new ProtocolException($this, $message) - ); + protected function onProtocolError($message) + { + Helpers::onCommunicationException(new ProtocolException($this, $message)); } - protected function onInvalidOption($option, $parameters = null) { + protected function onInvalidOption($option, $parameters = null) + { $message = "Invalid option: $option"; if (isset($parameters)) { $message .= " [$parameters]"; } + throw new InvalidArgumentException($message); } - public function getResource() { + public function getResource() + { if (isset($this->_resource)) { return $this->_resource; } + $this->connect(); + return $this->_resource; } - public function getParameters() { + public function getParameters() + { return $this->_params; } - protected function getIdentifier() { + protected function getIdentifier() + { if ($this->_params->scheme === 'unix') { return $this->_params->path; } + return "{$this->_params->host}:{$this->_params->port}"; } - public function __toString() { + public function __toString() + { if (!isset($this->_cachedId)) { $this->_cachedId = $this->getIdentifier(); } + return $this->_cachedId; } } diff --git a/lib/Predis/Network/ConnectionException.php b/lib/Predis/Network/ConnectionException.php index d7ab9696..eb4e4e6b 100644 --- a/lib/Predis/Network/ConnectionException.php +++ b/lib/Predis/Network/ConnectionException.php @@ -4,5 +4,6 @@ namespace Predis\Network; use Predis\CommunicationException; -class ConnectionException extends CommunicationException { +class ConnectionException extends CommunicationException +{ } diff --git a/lib/Predis/Network/IConnection.php b/lib/Predis/Network/IConnection.php index ea8a0a48..975e2f1d 100644 --- a/lib/Predis/Network/IConnection.php +++ b/lib/Predis/Network/IConnection.php @@ -4,7 +4,8 @@ namespace Predis\Network; use Predis\Commands\ICommand; -interface IConnection { +interface IConnection +{ public function connect(); public function disconnect(); public function isConnected(); diff --git a/lib/Predis/Network/IConnectionCluster.php b/lib/Predis/Network/IConnectionCluster.php index b48ea5d8..dc4ae9b6 100644 --- a/lib/Predis/Network/IConnectionCluster.php +++ b/lib/Predis/Network/IConnectionCluster.php @@ -4,7 +4,8 @@ namespace Predis\Network; use Predis\Commands\ICommand; -interface IConnectionCluster extends IConnection { +interface IConnectionCluster extends IConnection +{ public function add(IConnectionSingle $connection); public function getConnection(ICommand $command); public function getConnectionById($connectionId); diff --git a/lib/Predis/Network/IConnectionComposable.php b/lib/Predis/Network/IConnectionComposable.php index 250feaf7..7e5d7236 100644 --- a/lib/Predis/Network/IConnectionComposable.php +++ b/lib/Predis/Network/IConnectionComposable.php @@ -4,7 +4,8 @@ namespace Predis\Network; use Predis\Protocol\IProtocolProcessor; -interface IConnectionComposable extends IConnectionSingle { +interface IConnectionComposable extends IConnectionSingle +{ public function setProtocol(IProtocolProcessor $protocol); public function getProtocol(); public function writeBytes($buffer); diff --git a/lib/Predis/Network/IConnectionSingle.php b/lib/Predis/Network/IConnectionSingle.php index 3e90ecf6..78bfe7eb 100644 --- a/lib/Predis/Network/IConnectionSingle.php +++ b/lib/Predis/Network/IConnectionSingle.php @@ -4,7 +4,8 @@ namespace Predis\Network; use Predis\Commands\ICommand; -interface IConnectionSingle extends IConnection { +interface IConnectionSingle extends IConnection +{ public function __toString(); public function getResource(); public function getParameters(); diff --git a/lib/Predis/Network/PhpiredisConnection.php b/lib/Predis/Network/PhpiredisConnection.php index f71a1818..523b1d42 100644 --- a/lib/Predis/Network/PhpiredisConnection.php +++ b/lib/Predis/Network/PhpiredisConnection.php @@ -25,163 +25,211 @@ use Predis\ServerException; use Predis\IConnectionParameters; use Predis\Commands\ICommand; -class PhpiredisConnection extends ConnectionBase { +class PhpiredisConnection extends ConnectionBase +{ private $_reader; - public function __construct(IConnectionParameters $parameters) { + public function __construct(IConnectionParameters $parameters) + { if (!function_exists('socket_create')) { throw new ClientException( 'The socket extension must be loaded in order to be able to ' . 'use this connection class' ); } + parent::__construct($parameters); } - public function __destruct() { + public function __destruct() + { phpiredis_reader_destroy($this->_reader); + parent::__destruct(); } - protected function checkParameters(IConnectionParameters $parameters) { + protected function checkParameters(IConnectionParameters $parameters) + { if ($parameters->isSetByUser('iterable_multibulk')) { $this->onInvalidOption('iterable_multibulk', $parameters); } if ($parameters->isSetByUser('connection_persistent')) { $this->onInvalidOption('connection_persistent', $parameters); } + return parent::checkParameters($parameters); } - private function initializeReader($throw_errors = true) { + private function initializeReader($throw_errors = true) + { if (!function_exists('phpiredis_reader_create')) { throw new ClientException( 'The phpiredis extension must be loaded in order to be able to ' . 'use this connection class' ); } + $reader = phpiredis_reader_create(); + phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler($throw_errors)); + $this->_reader = $reader; } - protected function initializeProtocol(IConnectionParameters $parameters) { + protected function initializeProtocol(IConnectionParameters $parameters) + { $this->initializeReader($parameters->throw_errors); } - private function getStatusHandler() { + private function getStatusHandler() + { return function($payload) { switch ($payload) { case 'OK': return true; + case 'QUEUED': return new ResponseQueued(); + default: return $payload; } }; } - private function getErrorHandler($throwErrors = true) { + private function getErrorHandler($throwErrors = true) + { if ($throwErrors) { return function($errorMessage) { throw new ServerException($errorMessage); }; } + return function($errorMessage) { return new ResponseError($errorMessage); }; } - private function emitSocketError() { + private function emitSocketError() + { $errno = socket_last_error(); $errstr = socket_strerror($errno); + $this->disconnect(); + $this->onConnectionError(trim($errstr), $errno); } - protected function createResource() { + protected function createResource() + { $parameters = $this->_params; + $initializer = array($this, "{$parameters->scheme}SocketInitializer"); $socket = call_user_func($initializer, $parameters); + $this->setSocketOptions($socket, $parameters); + return $socket; } - private function tcpSocketInitializer(IConnectionParameters $parameters) { + private function tcpSocketInitializer(IConnectionParameters $parameters) + { $socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!is_resource($socket)) { $this->emitSocketError(); } + return $socket; } - private function unixSocketInitializer(IConnectionParameters $parameters) { + private function unixSocketInitializer(IConnectionParameters $parameters) + { $socket = @socket_create(AF_UNIX, SOCK_STREAM, 0); + if (!is_resource($socket)) { $this->emitSocketError(); } + return $socket; } - private function setSocketOptions($socket, IConnectionParameters $parameters) { + private function setSocketOptions($socket, IConnectionParameters $parameters) + { if ($parameters->scheme !== 'tcp') { return; } + if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) { $this->emitSocketError(); } + if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { $this->emitSocketError(); } + if (isset($parameters->read_write_timeout)) { $rwtimeout = $parameters->read_write_timeout; - $timeoutSec = floor($rwtimeout); + $timeoutSec = floor($rwtimeout); $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000; - $timeout = array('sec' => $timeoutSec, 'usec' => $timeoutUsec); + + $timeout = array( + 'sec' => $timeoutSec, + 'usec' => $timeoutUsec, + ); + if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) { $this->emitSocketError(); } + if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) { $this->emitSocketError(); } } } - private function getAddress(IConnectionParameters $parameters) { + private function getAddress(IConnectionParameters $parameters) + { if ($parameters->scheme === 'unix') { return $parameters->path; } + $host = $parameters->host; + if (ip2long($host) === false) { if (($address = gethostbyname($host)) === $host) { $this->onConnectionError("Cannot resolve the address of $host"); } return $address; } + return $host; } private function connectWithTimeout(IConnectionParameters $parameters) { $host = self::getAddress($parameters); $socket = $this->getResource(); + socket_set_nonblock($socket); + if (@socket_connect($socket, $host, $parameters->port) === false) { $error = socket_last_error(); if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) { $this->emitSocketError(); } } + socket_set_block($socket); $null = null; $selectable = array($socket); + $timeout = $parameters->connection_timeout; $timeoutSecs = floor($timeout); $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000; $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs); + if ($selected === 2) { $this->onConnectionError('Connection refused', SOCKET_ECONNREFUSED); } @@ -193,22 +241,27 @@ class PhpiredisConnection extends ConnectionBase { } } - public function connect() { + public function connect() + { parent::connect(); + $this->connectWithTimeout($this->_params); if (count($this->_initCmds) > 0) { $this->sendInitializationCommands(); } } - public function disconnect() { + public function disconnect() + { if ($this->isConnected()) { socket_close($this->getResource()); + parent::disconnect(); } } - private function sendInitializationCommands() { + private function sendInitializationCommands() + { foreach ($this->_initCmds as $command) { $this->writeCommand($command); } @@ -217,29 +270,37 @@ class PhpiredisConnection extends ConnectionBase { } } - private function write($buffer) { + private function write($buffer) + { $socket = $this->getResource(); + while (($length = strlen($buffer)) > 0) { $written = socket_write($socket, $buffer, $length); + if ($length === $written) { return; } if ($written === false) { $this->onConnectionError('Error while writing bytes to the server'); } + $buffer = substr($buffer, $written); } } - public function read() { + public function read() + { $socket = $this->getResource(); $reader = $this->_reader; + while (($state = phpiredis_reader_get_state($reader)) === PHPIREDIS_READER_STATE_INCOMPLETE) { if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '') { $this->emitSocketError(); } + phpiredis_reader_feed($reader, $buffer); } + if ($state === PHPIREDIS_READER_STATE_COMPLETE) { return phpiredis_reader_get_reply($reader); } @@ -248,7 +309,8 @@ class PhpiredisConnection extends ConnectionBase { } } - public function writeCommand(ICommand $command) { + public function writeCommand(ICommand $command) + { $cmdargs = $command->getArguments(); array_unshift($cmdargs, $command->getId()); $this->write(phpiredis_format_command($cmdargs)); diff --git a/lib/Predis/Network/PredisCluster.php b/lib/Predis/Network/PredisCluster.php index a03f8a26..a6926396 100644 --- a/lib/Predis/Network/PredisCluster.php +++ b/lib/Predis/Network/PredisCluster.php @@ -8,81 +8,101 @@ use Predis\Commands\ICommand; use Predis\Distribution\IDistributionStrategy; use Predis\Distribution\HashRing; -class PredisCluster implements IConnectionCluster, \IteratorAggregate { +class PredisCluster implements IConnectionCluster, \IteratorAggregate +{ private $_pool; private $_distributor; - public function __construct(IDistributionStrategy $distributor = null) { + public function __construct(IDistributionStrategy $distributor = null) + { $this->_pool = array(); $this->_distributor = $distributor ?: new HashRing(); } - public function isConnected() { + public function isConnected() + { foreach ($this->_pool as $connection) { if ($connection->isConnected()) { return true; } } + return false; } - public function connect() { + public function connect() + { foreach ($this->_pool as $connection) { $connection->connect(); } } - public function disconnect() { + public function disconnect() + { foreach ($this->_pool as $connection) { $connection->disconnect(); } } - public function add(IConnectionSingle $connection) { + public function add(IConnectionSingle $connection) + { $parameters = $connection->getParameters(); + if (isset($parameters->alias)) { $this->_pool[$parameters->alias] = $connection; } else { $this->_pool[] = $connection; } + $this->_distributor->add($connection, $parameters->weight); } - public function getConnection(ICommand $command) { + public function getConnection(ICommand $command) + { $cmdHash = $command->getHash($this->_distributor); + if (isset($cmdHash)) { return $this->_distributor->get($cmdHash); } + throw new ClientException( sprintf("Cannot send '%s' commands to a cluster of connections", $command->getId()) ); } - public function getConnectionById($id = null) { + public function getConnectionById($id = null) + { $alias = $id ?: 0; + return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null; } - public function getConnectionByKey($key) { + public function getConnectionByKey($key) + { $hashablePart = Helpers::getKeyHashablePart($key); $keyHash = $this->_distributor->generateKey($hashablePart); + return $this->_distributor->get($keyHash); } - public function getIterator() { + public function getIterator() + { return new \ArrayIterator($this->_pool); } - public function writeCommand(ICommand $command) { + public function writeCommand(ICommand $command) + { $this->getConnection($command)->writeCommand($command); } - public function readResponse(ICommand $command) { + public function readResponse(ICommand $command) + { return $this->getConnection($command)->readResponse($command); } - public function executeCommand(ICommand $command) { + public function executeCommand(ICommand $command) + { return $this->getConnection($command)->executeCommand($command); } } diff --git a/lib/Predis/Network/StreamConnection.php b/lib/Predis/Network/StreamConnection.php index 5cb390a8..ddebb25c 100644 --- a/lib/Predis/Network/StreamConnection.php +++ b/lib/Predis/Network/StreamConnection.php @@ -9,29 +9,36 @@ use Predis\IConnectionParameters; use Predis\Commands\ICommand; use Predis\Iterators\MultiBulkResponseSimple; -class StreamConnection extends ConnectionBase { +class StreamConnection extends ConnectionBase +{ private $_mbiterable; private $_throwErrors; - public function __destruct() { + public function __destruct() + { if (!$this->_params->connection_persistent) { $this->disconnect(); } } - protected function initializeProtocol(IConnectionParameters $parameters) { + protected function initializeProtocol(IConnectionParameters $parameters) + { $this->_throwErrors = $parameters->throw_errors; $this->_mbiterable = $parameters->iterable_multibulk; } - protected function createResource() { + protected function createResource() + { $parameters = $this->_params; $initializer = "{$parameters->scheme}StreamInitializer"; + return $this->$initializer($parameters); } - private function tcpStreamInitializer(IConnectionParameters $parameters) { + private function tcpStreamInitializer(IConnectionParameters $parameters) + { $uri = "tcp://{$parameters->host}:{$parameters->port}/"; + $flags = STREAM_CLIENT_CONNECT; if ($parameters->connection_async) { $flags |= STREAM_CLIENT_ASYNC_CONNECT; @@ -39,12 +46,15 @@ class StreamConnection extends ConnectionBase { if ($parameters->connection_persistent) { $flags |= STREAM_CLIENT_PERSISTENT; } + $resource = @stream_socket_client( $uri, $errno, $errstr, $parameters->connection_timeout, $flags ); + if (!$resource) { $this->onConnectionError(trim($errstr), $errno); } + if (isset($parameters->read_write_timeout)) { $rwtimeout = $parameters->read_write_timeout; $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1; @@ -52,39 +62,50 @@ class StreamConnection extends ConnectionBase { $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000; stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds); } + return $resource; } - private function unixStreamInitializer(IConnectionParameters $parameters) { + private function unixStreamInitializer(IConnectionParameters $parameters) + { $uri = "unix://{$parameters->path}"; + $flags = STREAM_CLIENT_CONNECT; if ($parameters->connection_persistent) { $flags |= STREAM_CLIENT_PERSISTENT; } + $resource = @stream_socket_client( $uri, $errno, $errstr, $parameters->connection_timeout, $flags ); + if (!$resource) { $this->onConnectionError(trim($errstr), $errno); } + return $resource; } - public function connect() { + public function connect() + { parent::connect(); + if (count($this->_initCmds) > 0){ $this->sendInitializationCommands(); } } - public function disconnect() { + public function disconnect() + { if ($this->isConnected()) { fclose($this->getResource()); + parent::disconnect(); } } - private function sendInitializationCommands() { + private function sendInitializationCommands() + { foreach ($this->_initCmds as $command) { $this->writeCommand($command); } @@ -93,8 +114,10 @@ class StreamConnection extends ConnectionBase { } } - protected function writeBytes($buffer) { + protected function writeBytes($buffer) + { $socket = $this->getResource(); + while (($length = strlen($buffer)) > 0) { $written = fwrite($socket, $buffer); if ($length === $written) { @@ -109,19 +132,24 @@ class StreamConnection extends ConnectionBase { public function read() { $socket = $this->getResource(); + $chunk = fgets($socket); if ($chunk === false || $chunk === '') { $this->onConnectionError('Error while reading line from the server'); } + $prefix = $chunk[0]; $payload = substr($chunk, 1, -2); + switch ($prefix) { case '+': // inline switch ($payload) { case 'OK': return true; + case 'QUEUED': return new ResponseQueued(); + default: return $payload; } @@ -131,8 +159,10 @@ class StreamConnection extends ConnectionBase { if ($size === -1) { return null; } + $bulkData = ''; $bytesLeft = ($size += 2); + do { $chunk = fread($socket, min($bytesLeft, 4096)); if ($chunk === false || $chunk === '') { @@ -143,6 +173,7 @@ class StreamConnection extends ConnectionBase { $bulkData .= $chunk; $bytesLeft = $size - strlen($bulkData); } while ($bytesLeft > 0); + return substr($bulkData, 0, -2); case '*': // multi bulk @@ -150,13 +181,16 @@ class StreamConnection extends ConnectionBase { 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(); } + return $multibulk; case ':': // integer @@ -173,7 +207,8 @@ class StreamConnection extends ConnectionBase { } } - public function writeCommand(ICommand $command) { + public function writeCommand(ICommand $command) + { $commandId = $command->getId(); $arguments = $command->getArguments(); @@ -181,11 +216,13 @@ class StreamConnection extends ConnectionBase { $reqlen = count($arguments) + 1; $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandId}\r\n"; + for ($i = 0; $i < $reqlen - 1; $i++) { $argument = $arguments[$i]; - $arglen = strlen($argument); + $arglen = strlen($argument); $buffer .= "\${$arglen}\r\n{$argument}\r\n"; } + $this->writeBytes($buffer); } } diff --git a/lib/Predis/Network/WebdisConnection.php b/lib/Predis/Network/WebdisConnection.php index 9de94cd7..2b195676 100644 --- a/lib/Predis/Network/WebdisConnection.php +++ b/lib/Predis/Network/WebdisConnection.php @@ -23,32 +23,39 @@ use Predis\Protocol\ProtocolException; const ERR_MSG_EXTENSION = 'The %s extension must be loaded in order to be able to use this connection class'; -class WebdisConnection implements IConnectionSingle { +class WebdisConnection implements IConnectionSingle +{ private $_parameters; private $_resource; private $_reader; - public function __construct(IConnectionParameters $parameters) { + public function __construct(IConnectionParameters $parameters) + { $this->_parameters = $parameters; + if ($parameters->scheme !== 'http') { throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}"); } + $this->checkExtensions(); $this->_resource = $this->initializeCurl($parameters); $this->_reader = $this->initializeReader($parameters); } - public function __destruct() { + public function __destruct() + { curl_close($this->_resource); phpiredis_reader_destroy($this->_reader); } - private function throwNotSupportedException($function) { + private function throwNotSupportedException($function) + { $class = __CLASS__; throw new \RuntimeException("The method $class::$function() is not supported"); } - private function checkExtensions() { + private function checkExtensions() + { if (!function_exists('curl_init')) { throw new ClientException(sprintf(ERR_MSG_EXTENSION, 'curl')); } @@ -57,7 +64,8 @@ class WebdisConnection implements IConnectionSingle { } } - private function initializeCurl(IConnectionParameters $parameters) { + private function initializeCurl(IConnectionParameters $parameters) + { $options = array( CURLOPT_FAILONERROR => true, CURLOPT_CONNECTTIMEOUT_MS => $parameters->connection_timeout * 1000, @@ -77,48 +85,60 @@ class WebdisConnection implements IConnectionSingle { return $resource; } - private function initializeReader(IConnectionParameters $parameters) { + private function initializeReader(IConnectionParameters $parameters) + { $reader = phpiredis_reader_create(); + phpiredis_reader_set_status_handler($reader, $this->getStatusHandler()); phpiredis_reader_set_error_handler($reader, $this->getErrorHandler($parameters->throw_errors)); + return $reader; } - private function getStatusHandler() { + private function getStatusHandler() + { return function($payload) { return $payload === 'OK' ? true : $payload; }; } - private function getErrorHandler($throwErrors) { + private function getErrorHandler($throwErrors) + { if ($throwErrors) { return function($errorMessage) { throw new ServerException($errorMessage); }; } + return function($errorMessage) { return new ResponseError($errorMessage); }; } - protected function feedReader($resource, $buffer) { + protected function feedReader($resource, $buffer) + { phpiredis_reader_feed($this->_reader, $buffer); + return strlen($buffer); } - public function connect() { + public function connect() + { // NOOP } - public function disconnect() { + public function disconnect() + { // NOOP } - public function isConnected() { + public function isConnected() + { return true; } - protected function getCommandId(ICommand $command) { + protected function getCommandId(ICommand $command) + { switch (($commandId = $command->getId())) { case 'AUTH': case 'SELECT': @@ -128,20 +148,24 @@ class WebdisConnection implements IConnectionSingle { case 'UNWATCH': case 'DISCARD': throw new \InvalidArgumentException("Disabled command: {$command->getId()}"); + default: return $commandId; } } - public function writeCommand(ICommand $command) { + public function writeCommand(ICommand $command) + { $this->throwNotSupportedException(__FUNCTION__); } - public function readResponse(ICommand $command) { + public function readResponse(ICommand $command) + { $this->throwNotSupportedException(__FUNCTION__); } - public function executeCommand(ICommand $command) { + public function executeCommand(ICommand $command) + { $resource = $this->_resource; $commandId = $this->getCommandId($command); @@ -154,6 +178,7 @@ class WebdisConnection implements IConnectionSingle { } curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand); + if (curl_exec($resource) === false) { $error = curl_error($resource); $errno = curl_errno($resource); @@ -161,6 +186,7 @@ class WebdisConnection implements IConnectionSingle { } $readerState = phpiredis_reader_get_state($this->_reader); + if ($readerState === PHPIREDIS_READER_STATE_COMPLETE) { $reply = phpiredis_reader_get_reply($this->_reader); if ($reply instanceof IReplyObject) { @@ -174,23 +200,28 @@ class WebdisConnection implements IConnectionSingle { } } - public function getResource() { + public function getResource() + { return $this->_resource; } - public function getParameters() { + public function getParameters() + { return $this->_parameters; } - public function pushInitCommand(ICommand $command) { + public function pushInitCommand(ICommand $command) + { $this->throwNotSupportedException(__FUNCTION__); } - public function read() { + public function read() + { $this->throwNotSupportedException(__FUNCTION__); } - public function __toString() { + public function __toString() + { return "{$this->_parameters->host}:{$this->_parameters->port}"; } } diff --git a/lib/Predis/Options/ClientCluster.php b/lib/Predis/Options/ClientCluster.php index 4771a798..25526525 100644 --- a/lib/Predis/Options/ClientCluster.php +++ b/lib/Predis/Options/ClientCluster.php @@ -5,28 +5,35 @@ namespace Predis\Options; use Predis\Network\IConnectionCluster; use Predis\Network\PredisCluster; -class ClientCluster extends Option { - protected function checkInstance($cluster) { +class ClientCluster extends Option +{ + protected function checkInstance($cluster) + { if (!$cluster instanceof IConnectionCluster) { throw new \InvalidArgumentException( 'Instance of Predis\Network\IConnectionCluster expected' ); } + return $cluster; } - public function validate($value) { + public function validate($value) + { if (is_callable($value)) { return $this->checkInstance(call_user_func($value)); } $initializer = $this->getInitializer($value); + return $this->checkInstance($initializer()); } - protected function getInitializer($fqnOrType) { + protected function getInitializer($fqnOrType) + { switch ($fqnOrType) { case 'predis': return function() { return new PredisCluster(); }; + default: return function() use($fqnOrType) { return new $fqnOrType(); @@ -34,7 +41,8 @@ class ClientCluster extends Option { } } - public function getDefault() { + public function getDefault() + { return new PredisCluster(); } } diff --git a/lib/Predis/Options/ClientConnectionFactory.php b/lib/Predis/Options/ClientConnectionFactory.php index 183ecc87..9cdd2d09 100644 --- a/lib/Predis/Options/ClientConnectionFactory.php +++ b/lib/Predis/Options/ClientConnectionFactory.php @@ -5,8 +5,10 @@ namespace Predis\Options; use Predis\IConnectionFactory; use Predis\ConnectionFactory; -class ClientConnectionFactory extends Option { - public function validate($value) { +class ClientConnectionFactory extends Option +{ + public function validate($value) + { if ($value instanceof IConnectionFactory) { return $value; } @@ -15,7 +17,8 @@ class ClientConnectionFactory extends Option { } } - public function getDefault() { + public function getDefault() + { return new ConnectionFactory(); } } diff --git a/lib/Predis/Options/ClientPrefix.php b/lib/Predis/Options/ClientPrefix.php index 962cf7f5..eb6f2dd8 100644 --- a/lib/Predis/Options/ClientPrefix.php +++ b/lib/Predis/Options/ClientPrefix.php @@ -4,8 +4,10 @@ namespace Predis\Options; use Predis\Commands\Processors\KeyPrefixProcessor; -class ClientPrefix extends Option { - public function validate($value) { +class ClientPrefix extends Option +{ + public function validate($value) + { return new KeyPrefixProcessor($value); } } diff --git a/lib/Predis/Options/ClientProfile.php b/lib/Predis/Options/ClientProfile.php index 9ed2d993..12357ec9 100644 --- a/lib/Predis/Options/ClientProfile.php +++ b/lib/Predis/Options/ClientProfile.php @@ -5,20 +5,25 @@ namespace Predis\Options; use Predis\Profiles\ServerProfile; use Predis\Profiles\IServerProfile; -class ClientProfile extends Option { - public function validate($value) { +class ClientProfile extends Option +{ + public function validate($value) + { if ($value instanceof IServerProfile) { return $value; } + if (is_string($value)) { return ServerProfile::get($value); } + throw new \InvalidArgumentException( "Invalid value for the profile option" ); } - public function getDefault() { + public function getDefault() + { return ServerProfile::getDefault(); } } diff --git a/lib/Predis/Options/CustomOption.php b/lib/Predis/Options/CustomOption.php index ae140ca2..a2642391 100644 --- a/lib/Predis/Options/CustomOption.php +++ b/lib/Predis/Options/CustomOption.php @@ -6,44 +6,54 @@ class CustomOption implements IOption { private $_validate; private $_default; - public function __construct(Array $options) { + public function __construct(Array $options) + { $this->_validate = $this->filterCallable($options, 'validate'); $this->_default = $this->filterCallable($options, 'default'); } - private function filterCallable($options, $key) { + private function filterCallable($options, $key) + { if (!isset($options[$key])) { return; } + $callable = $options[$key]; if (is_callable($callable)) { return $callable; } + throw new \InvalidArgumentException("The parameter $key must be callable"); } - public function validate($value) { + public function validate($value) + { if (isset($value)) { if ($this->_validate === null) { return $value; } $validator = $this->_validate; + return $validator($value); } } - public function getDefault() { + public function getDefault() + { if (!isset($this->_default)) { return; } $default = $this->_default; + return $default(); } - public function __invoke($value) { + public function __invoke($value) + { if (isset($value)) { return $this->validate($value); } + return $this->getDefault(); } } diff --git a/lib/Predis/Options/IOption.php b/lib/Predis/Options/IOption.php index 00b7b705..22edb0c3 100644 --- a/lib/Predis/Options/IOption.php +++ b/lib/Predis/Options/IOption.php @@ -2,7 +2,8 @@ namespace Predis\Options; -interface IOption { +interface IOption +{ public function validate($value); public function getDefault(); public function __invoke($value); diff --git a/lib/Predis/Options/Option.php b/lib/Predis/Options/Option.php index 8dd389ae..b80872b5 100644 --- a/lib/Predis/Options/Option.php +++ b/lib/Predis/Options/Option.php @@ -2,19 +2,24 @@ namespace Predis\Options; -class Option implements IOption { - public function validate($value) { +class Option implements IOption +{ + public function validate($value) + { return $value; } - public function getDefault() { + public function getDefault() + { return null; } - public function __invoke($value) { + public function __invoke($value) + { if (isset($value)) { return $this->validate($value); } + return $this->getDefault(); } } diff --git a/lib/Predis/Pipeline/FireAndForgetExecutor.php b/lib/Predis/Pipeline/FireAndForgetExecutor.php index ea5e8319..50fa7cdc 100644 --- a/lib/Predis/Pipeline/FireAndForgetExecutor.php +++ b/lib/Predis/Pipeline/FireAndForgetExecutor.php @@ -4,11 +4,14 @@ namespace Predis\Pipeline; use Predis\Network\IConnection; -class FireAndForgetExecutor implements IPipelineExecutor { - public function execute(IConnection $connection, &$commands) { +class FireAndForgetExecutor implements IPipelineExecutor +{ + public function execute(IConnection $connection, &$commands) + { foreach ($commands as $command) { $connection->writeCommand($command); } + $connection->disconnect(); return array(); diff --git a/lib/Predis/Pipeline/IPipelineExecutor.php b/lib/Predis/Pipeline/IPipelineExecutor.php index d0375b5a..f04f3d43 100644 --- a/lib/Predis/Pipeline/IPipelineExecutor.php +++ b/lib/Predis/Pipeline/IPipelineExecutor.php @@ -4,6 +4,7 @@ namespace Predis\Pipeline; use Predis\Network\IConnection; -interface IPipelineExecutor { +interface IPipelineExecutor +{ public function execute(IConnection $connection, &$commands); } diff --git a/lib/Predis/Pipeline/PipelineContext.php b/lib/Predis/Pipeline/PipelineContext.php index 7f58de38..c34cda30 100644 --- a/lib/Predis/Pipeline/PipelineContext.php +++ b/lib/Predis/Pipeline/PipelineContext.php @@ -7,22 +7,27 @@ use Predis\Helpers; use Predis\ClientException; use Predis\Commands\ICommand; -class PipelineContext { +class PipelineContext +{ private $_client; private $_executor; + private $_pipeline = array(); private $_replies = array(); private $_running = false; - public function __construct(Client $client, Array $options = null) { + public function __construct(Client $client, Array $options = null) + { $this->_client = $client; $this->_executor = $this->getExecutor($client, $options ?: array()); } - protected function getExecutor(Client $client, Array $options) { + protected function getExecutor(Client $client, Array $options) + { if (!$options) { return new StandardExecutor(); } + if (isset($options['executor'])) { $executor = $options['executor']; if (!$executor instanceof IPipelineExecutor) { @@ -33,45 +38,55 @@ class PipelineContext { } return $executor; } + if (isset($options['safe']) && $options['safe'] == true) { $isCluster = Helpers::isCluster($client->getConnection()); return $isCluster ? new SafeClusterExecutor() : new SafeExecutor(); } + return new StandardExecutor(); } - public function __call($method, $arguments) { + public function __call($method, $arguments) + { $command = $this->_client->createCommand($method, $arguments); $this->recordCommand($command); + return $this; } - protected function recordCommand(ICommand $command) { + protected function recordCommand(ICommand $command) + { $this->_pipeline[] = $command; } - public function executeCommand(ICommand $command) { + public function executeCommand(ICommand $command) + { $this->recordCommand($command); } - public function flushPipeline() { + public function flushPipeline() + { if (count($this->_pipeline) > 0) { $connection = $this->_client->getConnection(); $replies = $this->_executor->execute($connection, $this->_pipeline); $this->_replies = array_merge($this->_replies, $replies); $this->_pipeline = array(); } + return $this; } - private function setRunning($bool) { + private function setRunning($bool) + { if ($bool === true && $this->_running === true) { throw new ClientException("This pipeline is already opened"); } $this->_running = $bool; } - public function execute($block = null) { + public function execute($block = null) + { if ($block && !is_callable($block)) { throw new \InvalidArgumentException('Argument passed must be a callable object'); } diff --git a/lib/Predis/Pipeline/SafeClusterExecutor.php b/lib/Predis/Pipeline/SafeClusterExecutor.php index 2ab2750d..4696533b 100644 --- a/lib/Predis/Pipeline/SafeClusterExecutor.php +++ b/lib/Predis/Pipeline/SafeClusterExecutor.php @@ -6,17 +6,21 @@ use Predis\ServerException; use Predis\CommunicationException; use Predis\Network\IConnection; -class SafeClusterExecutor implements IPipelineExecutor { - public function execute(IConnection $connection, &$commands) { +class SafeClusterExecutor implements IPipelineExecutor +{ + public function execute(IConnection $connection, &$commands) + { $connectionExceptions = array(); $sizeofPipe = count($commands); $values = array(); foreach ($commands as $command) { $cmdConnection = $connection->getConnection($command); + if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) { continue; } + try { $cmdConnection->writeCommand($command); } @@ -39,10 +43,7 @@ class SafeClusterExecutor implements IPipelineExecutor { try { $response = $cmdConnection->readResponse($command); - $values[] = ($response instanceof \Iterator - ? iterator_to_array($response) - : $response - ); + $values[] = $response instanceof \Iterator ? iterator_to_array($response) : $response; } catch (ServerException $exception) { $values[] = $exception->toResponseError(); diff --git a/lib/Predis/Pipeline/SafeExecutor.php b/lib/Predis/Pipeline/SafeExecutor.php index 408d7900..375d6023 100644 --- a/lib/Predis/Pipeline/SafeExecutor.php +++ b/lib/Predis/Pipeline/SafeExecutor.php @@ -6,8 +6,10 @@ use Predis\ServerException; use Predis\CommunicationException; use Predis\Network\IConnection; -class SafeExecutor implements IPipelineExecutor { - public function execute(IConnection $connection, &$commands) { +class SafeExecutor implements IPipelineExecutor +{ + public function execute(IConnection $connection, &$commands) + { $sizeofPipe = count($commands); $values = array(); @@ -23,18 +25,16 @@ class SafeExecutor implements IPipelineExecutor { for ($i = 0; $i < $sizeofPipe; $i++) { $command = $commands[$i]; unset($commands[$i]); + try { $response = $connection->readResponse($command); - $values[] = ($response instanceof \Iterator - ? iterator_to_array($response) - : $response - ); + $values[] = $response instanceof \Iterator ? iterator_to_array($response) : $response; } catch (ServerException $exception) { $values[] = $exception->toResponseError(); } catch (CommunicationException $exception) { - $toAdd = count($commands) - count($values); + $toAdd = count($commands) - count($values); $values = array_merge($values, array_fill(0, $toAdd, $exception)); break; } diff --git a/lib/Predis/Pipeline/StandardExecutor.php b/lib/Predis/Pipeline/StandardExecutor.php index fcf885cd..0ab62535 100644 --- a/lib/Predis/Pipeline/StandardExecutor.php +++ b/lib/Predis/Pipeline/StandardExecutor.php @@ -5,14 +5,17 @@ namespace Predis\Pipeline; use Predis\ServerException; use Predis\Network\IConnection; -class StandardExecutor implements IPipelineExecutor { - public function execute(IConnection $connection, &$commands) { +class StandardExecutor implements IPipelineExecutor +{ + public function execute(IConnection $connection, &$commands) + { $sizeofPipe = count($commands); $values = array(); foreach ($commands as $command) { $connection->writeCommand($command); } + try { for ($i = 0; $i < $sizeofPipe; $i++) { $response = $connection->readResponse($commands[$i]); diff --git a/lib/Predis/PredisException.php b/lib/Predis/PredisException.php index ac1f968f..f97e1051 100644 --- a/lib/Predis/PredisException.php +++ b/lib/Predis/PredisException.php @@ -2,5 +2,6 @@ namespace Predis; -abstract class PredisException extends \Exception { +abstract class PredisException extends \Exception +{ } diff --git a/lib/Predis/Profiles/IServerProfile.php b/lib/Predis/Profiles/IServerProfile.php index abcf8c5c..01958cbb 100644 --- a/lib/Predis/Profiles/IServerProfile.php +++ b/lib/Predis/Profiles/IServerProfile.php @@ -2,7 +2,8 @@ namespace Predis\Profiles; -interface IServerProfile { +interface IServerProfile +{ public function getVersion(); public function supportsCommand($command); public function supportsCommands(Array $commands); diff --git a/lib/Predis/Profiles/ServerProfile.php b/lib/Predis/Profiles/ServerProfile.php index 0c320b82..fc677ffa 100644 --- a/lib/Predis/Profiles/ServerProfile.php +++ b/lib/Predis/Profiles/ServerProfile.php @@ -6,26 +6,32 @@ use Predis\ClientException; use Predis\Commands\Processors\ICommandProcessor; use Predis\Commands\Processors\IProcessingSupport; -abstract class ServerProfile implements IServerProfile, IProcessingSupport { +abstract class ServerProfile implements IServerProfile, IProcessingSupport +{ private static $_profiles; + private $_registeredCommands; private $_processor; - public function __construct() { + public function __construct() + { $this->_registeredCommands = $this->getSupportedCommands(); } protected abstract function getSupportedCommands(); - public static function getDefault() { + public static function getDefault() + { return self::get('default'); } - public static function getDevelopment() { + public static function getDevelopment() + { return self::get('dev'); } - private static function getDefaultProfiles() { + private static function getDefaultProfiles() + { return array( '1.2' => '\Predis\Profiles\ServerVersion12', '2.0' => '\Predis\Profiles\ServerVersion20', @@ -36,64 +42,80 @@ abstract class ServerProfile implements IServerProfile, IProcessingSupport { ); } - public static function define($alias, $profileClass) { + public static function define($alias, $profileClass) + { if (!isset(self::$_profiles)) { self::$_profiles = self::getDefaultProfiles(); } + $profileReflection = new \ReflectionClass($profileClass); + if (!$profileReflection->isSubclassOf('\Predis\Profiles\IServerProfile')) { throw new ClientException( "Cannot register '$profileClass' as it is not a valid profile class" ); } + self::$_profiles[$alias] = $profileClass; } - public static function get($version) { + public static function get($version) + { if (!isset(self::$_profiles)) { self::$_profiles = self::getDefaultProfiles(); } if (!isset(self::$_profiles[$version])) { throw new ClientException("Unknown server profile: $version"); } + $profile = self::$_profiles[$version]; + return new $profile(); } - public function supportsCommands(Array $commands) { + public function supportsCommands(Array $commands) + { foreach ($commands as $command) { if ($this->supportsCommand($command) === false) { return false; } } + return true; } - public function supportsCommand($command) { + public function supportsCommand($command) + { return isset($this->_registeredCommands[strtolower($command)]); } - public function createCommand($method, $arguments = array()) { + public function createCommand($method, $arguments = array()) + { $method = strtolower($method); if (!isset($this->_registeredCommands[$method])) { throw new ClientException("'$method' is not a registered Redis command"); } + $commandClass = $this->_registeredCommands[$method]; $command = new $commandClass(); $command->setArguments($arguments); + if (isset($this->_processor)) { $this->_processor->process($command); } + return $command; } - public function defineCommands(Array $commands) { + public function defineCommands(Array $commands) + { foreach ($commands as $alias => $command) { $this->defineCommand($alias, $command); } } - public function defineCommand($alias, $command) { + public function defineCommand($alias, $command) + { $commandReflection = new \ReflectionClass($command); if (!$commandReflection->isSubclassOf('\Predis\Commands\ICommand')) { throw new ClientException("Cannot register '$command' as it is not a valid Redis command"); @@ -101,7 +123,8 @@ abstract class ServerProfile implements IServerProfile, IProcessingSupport { $this->_registeredCommands[strtolower($alias)] = $command; } - public function setProcessor(ICommandProcessor $processor) { + public function setProcessor(ICommandProcessor $processor) + { if (!isset($processor)) { unset($this->_processor); return; @@ -109,11 +132,13 @@ abstract class ServerProfile implements IServerProfile, IProcessingSupport { $this->_processor = $processor; } - public function getProcessor() { + public function getProcessor() + { return $this->_processor; } - public function __toString() { + public function __toString() + { return $this->getVersion(); } } diff --git a/lib/Predis/Profiles/ServerVersion12.php b/lib/Predis/Profiles/ServerVersion12.php index 6a300628..3e0cac02 100644 --- a/lib/Predis/Profiles/ServerVersion12.php +++ b/lib/Predis/Profiles/ServerVersion12.php @@ -2,9 +2,15 @@ namespace Predis\Profiles; -class ServerVersion12 extends ServerProfile { - public function getVersion() { return '1.2'; } - public function getSupportedCommands() { +class ServerVersion12 extends ServerProfile +{ + public function getVersion() + { + return '1.2'; + } + + public function getSupportedCommands() + { return array( /* ---------------- Redis 1.2 ---------------- */ diff --git a/lib/Predis/Profiles/ServerVersion20.php b/lib/Predis/Profiles/ServerVersion20.php index 8bedaf3b..c2eea5ff 100644 --- a/lib/Predis/Profiles/ServerVersion20.php +++ b/lib/Predis/Profiles/ServerVersion20.php @@ -2,9 +2,15 @@ namespace Predis\Profiles; -class ServerVersion20 extends ServerProfile { - public function getVersion() { return '2.0'; } - public function getSupportedCommands() { +class ServerVersion20 extends ServerProfile +{ + public function getVersion() + { + return '2.0'; + } + + public function getSupportedCommands() + { return array( /* ---------------- Redis 1.2 ---------------- */ diff --git a/lib/Predis/Profiles/ServerVersion22.php b/lib/Predis/Profiles/ServerVersion22.php index 94760531..f1787b31 100644 --- a/lib/Predis/Profiles/ServerVersion22.php +++ b/lib/Predis/Profiles/ServerVersion22.php @@ -3,8 +3,13 @@ namespace Predis\Profiles; class ServerVersion22 extends ServerProfile { - public function getVersion() { return '2.2'; } - public function getSupportedCommands() { + public function getVersion() + { + return '2.2'; + } + + public function getSupportedCommands() + { return array( /* ---------------- Redis 1.2 ---------------- */ diff --git a/lib/Predis/Profiles/ServerVersion24.php b/lib/Predis/Profiles/ServerVersion24.php index 3a9b4022..35621077 100644 --- a/lib/Predis/Profiles/ServerVersion24.php +++ b/lib/Predis/Profiles/ServerVersion24.php @@ -3,8 +3,13 @@ namespace Predis\Profiles; class ServerVersion24 extends ServerProfile { - public function getVersion() { return '2.4'; } - public function getSupportedCommands() { + public function getVersion() + { + return '2.4'; + } + + public function getSupportedCommands() + { return array( /* ---------------- Redis 1.2 ---------------- */ diff --git a/lib/Predis/Profiles/ServerVersionNext.php b/lib/Predis/Profiles/ServerVersionNext.php index 2cb5cd7e..f9b97e7c 100644 --- a/lib/Predis/Profiles/ServerVersionNext.php +++ b/lib/Predis/Profiles/ServerVersionNext.php @@ -2,9 +2,15 @@ namespace Predis\Profiles; -class ServerVersionNext extends ServerVersion24 { - public function getVersion() { return '2.6'; } - public function getSupportedCommands() { +class ServerVersionNext extends ServerVersion24 +{ + public function getVersion() + { + return '2.6'; + } + + public function getSupportedCommands() + { return array_merge(parent::getSupportedCommands(), array( 'info' => '\Predis\Commands\ServerInfoV26x', 'eval' => '\Predis\Commands\ServerEval', diff --git a/lib/Predis/Protocol/ICommandSerializer.php b/lib/Predis/Protocol/ICommandSerializer.php index 9e4b5559..c154747f 100644 --- a/lib/Predis/Protocol/ICommandSerializer.php +++ b/lib/Predis/Protocol/ICommandSerializer.php @@ -4,6 +4,7 @@ namespace Predis\Protocol; use Predis\Commands\ICommand; -interface ICommandSerializer { +interface ICommandSerializer +{ public function serialize(ICommand $command); } diff --git a/lib/Predis/Protocol/IComposableProtocolProcessor.php b/lib/Predis/Protocol/IComposableProtocolProcessor.php index b0b283c7..870d64e6 100644 --- a/lib/Predis/Protocol/IComposableProtocolProcessor.php +++ b/lib/Predis/Protocol/IComposableProtocolProcessor.php @@ -2,7 +2,8 @@ namespace Predis\Protocol; -interface IComposableProtocolProcessor extends IProtocolProcessor { +interface IComposableProtocolProcessor extends IProtocolProcessor +{ public function setSerializer(ICommandSerializer $serializer); public function getSerializer(); public function setReader(IResponseReader $reader); diff --git a/lib/Predis/Protocol/IProtocolProcessor.php b/lib/Predis/Protocol/IProtocolProcessor.php index 48b9cd56..62aa6a72 100644 --- a/lib/Predis/Protocol/IProtocolProcessor.php +++ b/lib/Predis/Protocol/IProtocolProcessor.php @@ -5,7 +5,8 @@ namespace Predis\Protocol; use Predis\Commands\ICommand; use Predis\Network\IConnectionComposable; -interface IProtocolProcessor extends IResponseReader { +interface IProtocolProcessor extends IResponseReader +{ public function write(IConnectionComposable $connection, ICommand $command); public function setOption($option, $value); } diff --git a/lib/Predis/Protocol/IResponseHandler.php b/lib/Predis/Protocol/IResponseHandler.php index d895d056..661a6ddf 100644 --- a/lib/Predis/Protocol/IResponseHandler.php +++ b/lib/Predis/Protocol/IResponseHandler.php @@ -4,6 +4,7 @@ namespace Predis\Protocol; use Predis\Network\IConnectionComposable; -interface IResponseHandler { +interface IResponseHandler +{ function handle(IConnectionComposable $connection, $payload); } diff --git a/lib/Predis/Protocol/IResponseReader.php b/lib/Predis/Protocol/IResponseReader.php index 15dd3bd5..c62fb696 100644 --- a/lib/Predis/Protocol/IResponseReader.php +++ b/lib/Predis/Protocol/IResponseReader.php @@ -4,6 +4,7 @@ namespace Predis\Protocol; use Predis\Network\IConnectionComposable; -interface IResponseReader { +interface IResponseReader +{ public function read(IConnectionComposable $connection); } diff --git a/lib/Predis/Protocol/ProtocolException.php b/lib/Predis/Protocol/ProtocolException.php index b1992a06..b37406a0 100644 --- a/lib/Predis/Protocol/ProtocolException.php +++ b/lib/Predis/Protocol/ProtocolException.php @@ -4,5 +4,6 @@ namespace Predis\Protocol; use Predis\CommunicationException; -class ProtocolException extends CommunicationException { +class ProtocolException extends CommunicationException +{ } diff --git a/lib/Predis/Protocol/Text/ComposableTextProtocol.php b/lib/Predis/Protocol/Text/ComposableTextProtocol.php index 3fe252b9..e76e23db 100644 --- a/lib/Predis/Protocol/Text/ComposableTextProtocol.php +++ b/lib/Predis/Protocol/Text/ComposableTextProtocol.php @@ -8,65 +8,78 @@ use Predis\Protocol\ICommandSerializer; use Predis\Protocol\IComposableProtocolProcessor; use Predis\Network\IConnectionComposable; -class ComposableTextProtocol implements IComposableProtocolProcessor { - private $_serializer, $_reader; +class ComposableTextProtocol implements IComposableProtocolProcessor +{ + private $_serializer; + private $_reader; - public function __construct(Array $options = array()) { + public function __construct(Array $options = array()) + { $this->setSerializer(new TextCommandSerializer()); $this->setReader(new TextResponseReader()); + if (count($options) > 0) { $this->initializeOptions($options); } } - private function initializeOptions(Array $options) { + private function initializeOptions(Array $options) + { foreach ($options as $k => $v) { $this->setOption($k, $v); } } - public function setOption($option, $value) { + public function setOption($option, $value) + { switch ($option) { case 'iterable_multibulk': $handler = $value ? new ResponseMultiBulkStreamHandler() : new ResponseMultiBulkHandler(); $this->_reader->setHandler(TextProtocol::PREFIX_MULTI_BULK, $handler); break; + case 'throw_errors': $handler = $value ? new ResponseErrorHandler() : new ResponseErrorSilentHandler(); $this->_reader->setHandler(TextProtocol::PREFIX_ERROR, $handler); break; + default: - throw new \InvalidArgumentException( - "The option $option is not supported by the current protocol" - ); + throw new \InvalidArgumentException("The option $option is not supported by the current protocol"); } } - public function serialize(ICommand $command) { + public function serialize(ICommand $command) + { return $this->_serializer->serialize($command); } - public function write(IConnectionComposable $connection, ICommand $command) { + public function write(IConnectionComposable $connection, ICommand $command) + { $connection->writeBytes($this->_serializer->serialize($command)); } - public function read(IConnectionComposable $connection) { + public function read(IConnectionComposable $connection) + { return $this->_reader->read($connection); } - public function setSerializer(ICommandSerializer $serializer) { + public function setSerializer(ICommandSerializer $serializer) + { $this->_serializer = $serializer; } - public function getSerializer() { + public function getSerializer() + { return $this->_serializer; } - public function setReader(IResponseReader $reader) { + public function setReader(IResponseReader $reader) + { $this->_reader = $reader; } - public function getReader() { + public function getReader() + { return $this->_reader; } } diff --git a/lib/Predis/Protocol/Text/ResponseBulkHandler.php b/lib/Predis/Protocol/Text/ResponseBulkHandler.php index 16388bd1..14f8986b 100644 --- a/lib/Predis/Protocol/Text/ResponseBulkHandler.php +++ b/lib/Predis/Protocol/Text/ResponseBulkHandler.php @@ -7,17 +7,22 @@ use Predis\Protocol\IResponseHandler; use Predis\Protocol\ProtocolException; use Predis\Network\IConnectionComposable; -class ResponseBulkHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $lengthString) { +class ResponseBulkHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $lengthString) + { $length = (int) $lengthString; + if ($length != $lengthString) { Helpers::onCommunicationException(new ProtocolException( $connection, "Cannot parse '$length' as data length" )); } + if ($length >= 0) { return substr($connection->readBytes($length + 2), 0, -2); } + if ($length == -1) { return null; } diff --git a/lib/Predis/Protocol/Text/ResponseErrorHandler.php b/lib/Predis/Protocol/Text/ResponseErrorHandler.php index 731984c7..d17dae78 100644 --- a/lib/Predis/Protocol/Text/ResponseErrorHandler.php +++ b/lib/Predis/Protocol/Text/ResponseErrorHandler.php @@ -6,8 +6,10 @@ use Predis\ServerException; use Predis\Protocol\IResponseHandler; use Predis\Network\IConnectionComposable; -class ResponseErrorHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $errorMessage) { +class ResponseErrorHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $errorMessage) + { throw new ServerException($errorMessage); } } diff --git a/lib/Predis/Protocol/Text/ResponseErrorSilentHandler.php b/lib/Predis/Protocol/Text/ResponseErrorSilentHandler.php index 3f7f2eae..8e2b9283 100644 --- a/lib/Predis/Protocol/Text/ResponseErrorSilentHandler.php +++ b/lib/Predis/Protocol/Text/ResponseErrorSilentHandler.php @@ -6,8 +6,10 @@ use Predis\ResponseError; use Predis\Protocol\IResponseHandler; use Predis\Network\IConnectionComposable; -class ResponseErrorSilentHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $errorMessage) { +class ResponseErrorSilentHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $errorMessage) + { return new ResponseError($errorMessage); } } diff --git a/lib/Predis/Protocol/Text/ResponseIntegerHandler.php b/lib/Predis/Protocol/Text/ResponseIntegerHandler.php index 2cb14e85..bca439c7 100644 --- a/lib/Predis/Protocol/Text/ResponseIntegerHandler.php +++ b/lib/Predis/Protocol/Text/ResponseIntegerHandler.php @@ -7,16 +7,20 @@ use Predis\Protocol\IResponseHandler; use Predis\Protocol\ProtocolException; use Predis\Network\IConnectionComposable; -class ResponseIntegerHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $number) { +class ResponseIntegerHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $number) + { if (is_numeric($number)) { return (int) $number; } + if ($number !== 'nil') { Helpers::onCommunicationException(new ProtocolException( $connection, "Cannot parse '$number' as numeric response" )); } + return null; } } diff --git a/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php b/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php index 6e30365a..77521c8f 100644 --- a/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php +++ b/lib/Predis/Protocol/Text/ResponseMultiBulkHandler.php @@ -7,9 +7,12 @@ use Predis\Protocol\IResponseHandler; use Predis\Protocol\ProtocolException; use Predis\Network\IConnectionComposable; -class ResponseMultiBulkHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $lengthString) { +class ResponseMultiBulkHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $lengthString) + { $length = (int) $lengthString; + if ($length != $lengthString) { Helpers::onCommunicationException(new ProtocolException( $connection, "Cannot parse '$length' as data length" @@ -21,12 +24,15 @@ class ResponseMultiBulkHandler implements IResponseHandler { } $list = array(); + if ($length > 0) { $handlersCache = array(); $reader = $connection->getProtocol()->getReader(); + for ($i = 0; $i < $length; $i++) { $header = $connection->readLine(); $prefix = $header[0]; + if (isset($handlersCache[$prefix])) { $handler = $handlersCache[$prefix]; } @@ -34,9 +40,11 @@ class ResponseMultiBulkHandler implements IResponseHandler { $handler = $reader->getHandler($prefix); $handlersCache[$prefix] = $handler; } + $list[$i] = $handler->handle($connection, substr($header, 1)); } } + return $list; } } diff --git a/lib/Predis/Protocol/Text/ResponseMultiBulkStreamHandler.php b/lib/Predis/Protocol/Text/ResponseMultiBulkStreamHandler.php index 0d5cd35b..82970dc7 100644 --- a/lib/Predis/Protocol/Text/ResponseMultiBulkStreamHandler.php +++ b/lib/Predis/Protocol/Text/ResponseMultiBulkStreamHandler.php @@ -8,14 +8,18 @@ use Predis\Protocol\ProtocolException; use Predis\Network\IConnectionComposable; use Predis\Iterators\MultiBulkResponseSimple; -class ResponseMultiBulkStreamHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $lengthString) { +class ResponseMultiBulkStreamHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $lengthString) + { $length = (int) $lengthString; + if ($length != $lengthString) { Helpers::onCommunicationException(new ProtocolException( $connection, "Cannot parse '$length' as data length" )); } + return new MultiBulkResponseSimple($connection, $length); } } diff --git a/lib/Predis/Protocol/Text/ResponseStatusHandler.php b/lib/Predis/Protocol/Text/ResponseStatusHandler.php index 21fef43c..581b3e7d 100644 --- a/lib/Predis/Protocol/Text/ResponseStatusHandler.php +++ b/lib/Predis/Protocol/Text/ResponseStatusHandler.php @@ -6,13 +6,17 @@ use Predis\ResponseQueued; use Predis\Protocol\IResponseHandler; use Predis\Network\IConnectionComposable; -class ResponseStatusHandler implements IResponseHandler { - public function handle(IConnectionComposable $connection, $status) { +class ResponseStatusHandler implements IResponseHandler +{ + public function handle(IConnectionComposable $connection, $status) + { switch ($status) { case 'OK': return true; + case 'QUEUED': return new ResponseQueued(); + default: return $status; } diff --git a/lib/Predis/Protocol/Text/TextCommandSerializer.php b/lib/Predis/Protocol/Text/TextCommandSerializer.php index 5725cebb..486636f2 100644 --- a/lib/Predis/Protocol/Text/TextCommandSerializer.php +++ b/lib/Predis/Protocol/Text/TextCommandSerializer.php @@ -5,8 +5,10 @@ namespace Predis\Protocol\Text; use Predis\Commands\ICommand; use Predis\Protocol\ICommandSerializer; -class TextCommandSerializer implements ICommandSerializer { - public function serialize(ICommand $command) { +class TextCommandSerializer implements ICommandSerializer +{ + public function serialize(ICommand $command) + { $commandId = $command->getId(); $arguments = $command->getArguments(); @@ -14,9 +16,10 @@ class TextCommandSerializer implements ICommandSerializer { $reqlen = count($arguments) + 1; $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandId}\r\n"; + for ($i = 0; $i < $reqlen - 1; $i++) { $argument = $arguments[$i]; - $arglen = strlen($argument); + $arglen = strlen($argument); $buffer .= "\${$arglen}\r\n{$argument}\r\n"; } diff --git a/lib/Predis/Protocol/Text/TextProtocol.php b/lib/Predis/Protocol/Text/TextProtocol.php index 2ac1947b..3c66f0f3 100644 --- a/lib/Predis/Protocol/Text/TextProtocol.php +++ b/lib/Predis/Protocol/Text/TextProtocol.php @@ -12,7 +12,8 @@ use Predis\Protocol\ProtocolException; use Predis\Network\IConnectionComposable; use Predis\Iterators\MultiBulkResponseSimple; -class TextProtocol implements IProtocolProcessor { +class TextProtocol implements IProtocolProcessor +{ const NEWLINE = "\r\n"; const OK = 'OK'; const ERROR = 'ERR'; @@ -27,29 +28,37 @@ class TextProtocol implements IProtocolProcessor { const BUFFER_SIZE = 4096; - private $_mbiterable, $_throwErrors, $_serializer; + private $_mbiterable; + private $_throwErrors; + private $_serializer; - public function __construct() { + public function __construct() + { $this->_mbiterable = false; $this->_throwErrors = true; $this->_serializer = new TextCommandSerializer(); } - public function write(IConnectionComposable $connection, ICommand $command) { + public function write(IConnectionComposable $connection, ICommand $command) + { $connection->writeBytes($this->_serializer->serialize($command)); } - public function read(IConnectionComposable $connection) { + public function read(IConnectionComposable $connection) + { $chunk = $connection->readLine(); $prefix = $chunk[0]; $payload = substr($chunk, 1); + switch ($prefix) { case '+': // inline switch ($payload) { case 'OK': return true; + case 'QUEUED': return new ResponseQueued(); + default: return $payload; } @@ -63,16 +72,19 @@ class TextProtocol implements IProtocolProcessor { case '*': // multi bulk $count = (int) $payload; + if ($count === -1) { return null; } if ($this->_mbiterable == true) { return new MultiBulkResponseSimple($connection, $count); } + $multibulk = array(); for ($i = 0; $i < $count; $i++) { $multibulk[$i] = $this->read($connection); } + return $multibulk; case ':': // integer @@ -91,11 +103,13 @@ class TextProtocol implements IProtocolProcessor { } } - public function setOption($option, $value) { + public function setOption($option, $value) + { switch ($option) { case 'iterable_multibulk': $this->_mbiterable = (bool) $value; break; + case 'throw_errors': $this->_throwErrors = (bool) $value; break; diff --git a/lib/Predis/Protocol/Text/TextResponseReader.php b/lib/Predis/Protocol/Text/TextResponseReader.php index 590d015b..57f2352b 100644 --- a/lib/Predis/Protocol/Text/TextResponseReader.php +++ b/lib/Predis/Protocol/Text/TextResponseReader.php @@ -8,14 +8,17 @@ use Predis\Protocol\IResponseHandler; use Predis\Protocol\ProtocolException; use Predis\Network\IConnectionComposable; -class TextResponseReader implements IResponseReader { +class TextResponseReader implements IResponseReader +{ private $_prefixHandlers; - public function __construct() { + public function __construct() + { $this->_prefixHandlers = $this->getDefaultHandlers(); } - private function getDefaultHandlers() { + private function getDefaultHandlers() + { return array( TextProtocol::PREFIX_STATUS => new ResponseStatusHandler(), TextProtocol::PREFIX_ERROR => new ResponseErrorHandler(), @@ -25,17 +28,20 @@ class TextResponseReader implements IResponseReader { ); } - public function setHandler($prefix, IResponseHandler $handler) { + public function setHandler($prefix, IResponseHandler $handler) + { $this->_prefixHandlers[$prefix] = $handler; } - public function getHandler($prefix) { + public function getHandler($prefix) + { if (isset($this->_prefixHandlers[$prefix])) { return $this->_prefixHandlers[$prefix]; } } - public function read(IConnectionComposable $connection) { + public function read(IConnectionComposable $connection) + { $header = $connection->readLine(); if ($header === '') { $this->protocolError($connection, 'Unexpected empty header'); @@ -45,11 +51,14 @@ class TextResponseReader implements IResponseReader { if (!isset($this->_prefixHandlers[$prefix])) { $this->protocolError($connection, "Unknown prefix '$prefix'"); } + $handler = $this->_prefixHandlers[$prefix]; + return $handler->handle($connection, substr($header, 1)); } - private function protocolError(IConnectionComposable $connection, $message) { + private function protocolError(IConnectionComposable $connection, $message) + { Helpers::onCommunicationException(new ProtocolException($connection, $message)); } } diff --git a/lib/Predis/PubSubContext.php b/lib/Predis/PubSubContext.php index 0800880a..47a0b555 100644 --- a/lib/Predis/PubSubContext.php +++ b/lib/Predis/PubSubContext.php @@ -2,7 +2,8 @@ namespace Predis; -class PubSubContext implements \Iterator { +class PubSubContext implements \Iterator +{ const SUBSCRIBE = 'subscribe'; const UNSUBSCRIBE = 'unsubscribe'; const PSUBSCRIBE = 'psubscribe'; @@ -18,27 +19,32 @@ class PubSubContext implements \Iterator { private $_position; private $_options; - public function __construct(Client $client, Array $options = null) { + public function __construct(Client $client, Array $options = null) + { $this->checkCapabilities($client); $this->_options = $options ?: array(); - $this->_client = $client; + $this->_client = $client; $this->_statusFlags = self::STATUS_VALID; $this->genericSubscribeInit('subscribe'); $this->genericSubscribeInit('psubscribe'); } - public function __destruct() { + public function __destruct() + { $this->closeContext(); } - private function checkCapabilities(Client $client) { + private function checkCapabilities(Client $client) + { if (Helpers::isCluster($client->getConnection())) { throw new ClientException( 'Cannot initialize a PUB/SUB context over a cluster of connections' ); } + $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe'); + if ($client->getProfile()->supportsCommands($commands) === false) { throw new ClientException( 'The current profile does not support PUB/SUB related commands' @@ -46,35 +52,42 @@ class PubSubContext implements \Iterator { } } - private function genericSubscribeInit($subscribeAction) { + private function genericSubscribeInit($subscribeAction) + { if (isset($this->_options[$subscribeAction])) { $this->$subscribeAction($this->_options[$subscribeAction]); } } - private function isFlagSet($value) { + private function isFlagSet($value) + { return ($this->_statusFlags & $value) === $value; } - public function subscribe(/* arguments */) { + public function subscribe(/* arguments */) + { $this->writeCommand(self::SUBSCRIBE, func_get_args()); $this->_statusFlags |= self::STATUS_SUBSCRIBED; } - public function unsubscribe(/* arguments */) { + public function unsubscribe(/* arguments */) + { $this->writeCommand(self::UNSUBSCRIBE, func_get_args()); } - public function psubscribe(/* arguments */) { + public function psubscribe(/* arguments */) + { $this->writeCommand(self::PSUBSCRIBE, func_get_args()); $this->_statusFlags |= self::STATUS_PSUBSCRIBED; } - public function punsubscribe(/* arguments */) { + public function punsubscribe(/* arguments */) + { $this->writeCommand(self::PUNSUBSCRIBE, func_get_args()); } - public function closeContext() { + public function closeContext() + { if ($this->valid()) { if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) { $this->unsubscribe(); @@ -85,44 +98,55 @@ class PubSubContext implements \Iterator { } } - private function writeCommand($method, $arguments) { + private function writeCommand($method, $arguments) + { $arguments = Helpers::filterArrayArguments($arguments); $command = $this->_client->createCommand($method, $arguments); $this->_client->getConnection()->writeCommand($command); } - public function rewind() { + public function rewind() + { // NOOP } - public function current() { + public function current() + { return $this->getValue(); } - public function key() { + public function key() + { return $this->_position; } - public function next() { + public function next() + { if ($this->isFlagSet(self::STATUS_VALID)) { $this->_position++; } + return $this->_position; } - public function valid() { + public function valid() + { $isValid = $this->isFlagSet(self::STATUS_VALID); $subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED; $hasSubscriptions = ($this->_statusFlags & $subscriptionFlags) > 0; + return $isValid && $hasSubscriptions; } - private function invalidate() { + private function invalidate() + { $this->_statusFlags = 0x0000; } - private function getValue() { + private function getValue() + { $response = $this->_client->getConnection()->read(); + switch ($response[0]) { case self::SUBSCRIBE: case self::UNSUBSCRIBE: @@ -131,12 +155,14 @@ class PubSubContext implements \Iterator { if ($response[2] === 0) { $this->invalidate(); } + case self::MESSAGE: return (object) array( 'kind' => $response[0], 'channel' => $response[1], 'payload' => $response[2], ); + case self::PMESSAGE: return (object) array( 'kind' => $response[0], @@ -144,6 +170,7 @@ class PubSubContext implements \Iterator { 'channel' => $response[2], 'payload' => $response[3], ); + default: throw new ClientException( "Received an unknown message type {$response[0]} inside of a pubsub context" diff --git a/lib/Predis/ResponseError.php b/lib/Predis/ResponseError.php index 135063cd..8f32f59a 100644 --- a/lib/Predis/ResponseError.php +++ b/lib/Predis/ResponseError.php @@ -2,23 +2,28 @@ namespace Predis; -class ResponseError implements IRedisServerError { +class ResponseError implements IRedisServerError +{ private $_message; - public function __construct($message) { + public function __construct($message) + { $this->_message = $message; } - public function getMessage() { + public function getMessage() + { return $this->_message; } - public function getErrorType() { + public function getErrorType() + { list($errorType, ) = explode(' ', $this->getMessage(), 2); return $errorType; } - public function __toString() { + public function __toString() + { return $this->getMessage(); } } diff --git a/lib/Predis/ResponseQueued.php b/lib/Predis/ResponseQueued.php index d282f28f..4fd98fb7 100644 --- a/lib/Predis/ResponseQueued.php +++ b/lib/Predis/ResponseQueued.php @@ -2,16 +2,20 @@ namespace Predis; -class ResponseQueued implements IReplyObject { - public function __toString() { +class ResponseQueued implements IReplyObject +{ + public function __toString() + { return 'QUEUED'; } - public function __get($property) { + public function __get($property) + { return $property === 'queued'; } - public function __isset($property) { + public function __isset($property) + { return $property === 'queued'; } } diff --git a/lib/Predis/ServerException.php b/lib/Predis/ServerException.php index 6a6d7304..3f97aca6 100644 --- a/lib/Predis/ServerException.php +++ b/lib/Predis/ServerException.php @@ -2,13 +2,16 @@ namespace Predis; -class ServerException extends PredisException implements IRedisServerError { - public function getErrorType() { +class ServerException extends PredisException implements IRedisServerError +{ + public function getErrorType() + { list($errorType, ) = explode(' ', $this->getMessage(), 2); return $errorType; } - public function toResponseError() { + public function toResponseError() + { return new ResponseError($this->getMessage()); } } diff --git a/lib/Predis/Transaction/AbortedMultiExecException.php b/lib/Predis/Transaction/AbortedMultiExecException.php index 6da356d1..a8fbe996 100644 --- a/lib/Predis/Transaction/AbortedMultiExecException.php +++ b/lib/Predis/Transaction/AbortedMultiExecException.php @@ -4,15 +4,19 @@ namespace Predis\Transaction; use Predis\PredisException; -class AbortedMultiExecException extends PredisException { +class AbortedMultiExecException extends PredisException +{ private $_transaction; - public function __construct(MultiExecContext $transaction, $message, $code = null) { - $this->_transaction = $transaction; + public function __construct(MultiExecContext $transaction, $message, $code = null) + { parent::__construct($message, $code); + + $this->_transaction = $transaction; } - public function getTransaction() { + public function getTransaction() + { return $this->_transaction; } } diff --git a/lib/Predis/Transaction/MultiExecContext.php b/lib/Predis/Transaction/MultiExecContext.php index f0649587..f5f188c8 100644 --- a/lib/Predis/Transaction/MultiExecContext.php +++ b/lib/Predis/Transaction/MultiExecContext.php @@ -10,7 +10,8 @@ use Predis\ServerException; use Predis\CommunicationException; use Predis\Protocol\ProtocolException; -class MultiExecContext { +class MultiExecContext +{ const STATE_RESET = 0x00000; const STATE_INITIALIZED = 0x00001; const STATE_INSIDEBLOCK = 0x00010; @@ -20,53 +21,65 @@ class MultiExecContext { private $_state; private $_canWatch; + protected $_client; protected $_options; protected $_commands; - public function __construct(Client $client, Array $options = null) { + public function __construct(Client $client, Array $options = null) + { $this->checkCapabilities($client); $this->_options = $options ?: array(); - $this->_client = $client; + $this->_client = $client; $this->reset(); } - protected function setState($flags) { + protected function setState($flags) + { $this->_state = $flags; } - protected function getState() { + protected function getState() + { return $this->_state; } - protected function flagState($flags) { + protected function flagState($flags) + { $this->_state |= $flags; } - protected function unflagState($flags) { + protected function unflagState($flags) + { $this->_state &= ~$flags; } - protected function checkState($flags) { + protected function checkState($flags) + { return ($this->_state & $flags) === $flags; } - private function checkCapabilities(Client $client) { + private function checkCapabilities(Client $client) + { if (Helpers::isCluster($client->getConnection())) { throw new ClientException( 'Cannot initialize a MULTI/EXEC context over a cluster of connections' ); } + $profile = $client->getProfile(); + if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) { throw new ClientException( 'The current profile does not support MULTI, EXEC and DISCARD' ); } + $this->_canWatch = $profile->supportsCommands(array('watch', 'unwatch')); } - private function isWatchSupported() { + private function isWatchSupported() + { if ($this->_canWatch === false) { throw new ClientException( 'The current profile does not support WATCH and UNWATCH' @@ -74,60 +87,78 @@ class MultiExecContext { } } - protected function reset() { + protected function reset() + { $this->setState(self::STATE_RESET); $this->_commands = array(); } - protected function initialize() { + 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) { + public function __call($method, $arguments) + { $this->initialize(); $client = $this->_client; + if ($this->checkState(self::STATE_CAS)) { return call_user_func_array(array($client, $method), $arguments); } + $command = $client->createCommand($method, $arguments); $response = $client->executeCommand($command); + if (!$response instanceof ResponseQueued) { $this->onProtocolError('The server did not respond with a QUEUED status reply'); } + $this->_commands[] = $command; + return $this; } - public function watch($keys) { + 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'); } + $watchReply = $this->_client->watch($keys); $this->flagState(self::STATE_WATCH); + return $watchReply; } - public function multi() { + public function multi() + { if ($this->checkState(self::STATE_INITIALIZED | self::STATE_CAS)) { $this->unflagState(self::STATE_CAS); $this->_client->multi(); @@ -135,42 +166,51 @@ class MultiExecContext { else { $this->initialize(); } + return $this; } - public function unwatch() { + public function unwatch() + { $this->isWatchSupported(); $this->unflagState(self::STATE_WATCH); $this->_client->unwatch(); + return $this; } - public function discard() { + 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() { + public function exec() + { return $this->execute(); } - private function checkBeforeExecution($block) { + private function checkBeforeExecution($block) + { if ($this->checkState(self::STATE_INSIDEBLOCK)) { throw new ClientException( "Cannot invoke 'execute' or 'exec' inside an active client transaction block" ); } + if ($block) { if (!is_callable($block)) { throw new \InvalidArgumentException( 'Argument passed must be a callable object' ); } + if (count($this->_commands) > 0) { $this->discard(); throw new ClientException( @@ -178,6 +218,7 @@ class MultiExecContext { ); } } + if (isset($this->_options['retry']) && !isset($block)) { $this->discard(); throw new \InvalidArgumentException( @@ -186,7 +227,8 @@ class MultiExecContext { } } - public function execute($block = null) { + public function execute($block = null) + { $this->checkBeforeExecution($block); $reply = null; @@ -206,32 +248,40 @@ class MultiExecContext { } $reply = $this->_client->exec(); + if ($reply === null) { if ($attemptsLeft === 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, $attemptsLeft); } + continue; } + break; } while ($attemptsLeft-- > 0); $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply; $sizeofReplies = count($execReply); - $commands = $this->_commands; + if ($sizeofReplies !== count($commands)) { $this->onProtocolError("EXEC returned an unexpected number of replies"); } + for ($i = 0; $i < $sizeofReplies; $i++) { $commandReply = $execReply[$i]; + if ($commandReply instanceof \Iterator) { $commandReply = iterator_to_array($commandReply); } + $returnValues[$i] = $commands[$i]->parseResponse($commandReply); unset($commands[$i]); } @@ -239,9 +289,11 @@ class MultiExecContext { return $returnValues; } - protected function executeTransactionBlock($block) { + protected function executeTransactionBlock($block) + { $blockException = null; $this->flagState(self::STATE_INSIDEBLOCK); + try { $block($this); } @@ -255,13 +307,16 @@ class MultiExecContext { $blockException = $exception; $this->discard(); } + $this->unflagState(self::STATE_INSIDEBLOCK); + if ($blockException !== null) { throw $blockException; } } - private function onProtocolError($message) { + private function onProtocolError($message) + { // Since a MULTI/EXEC block cannot be initialized over a clustered // connection, we can safely assume that Predis\Client::getConnection() // will always return an instance of Predis\Network\IConnectionSingle. diff --git a/test/ClientFeaturesTest.php b/test/ClientFeaturesTest.php index 61aec604..32c357a9 100644 --- a/test/ClientFeaturesTest.php +++ b/test/ClientFeaturesTest.php @@ -1,26 +1,32 @@ redis = RC::getConnection(); $this->redis->flushdb(); } - protected function tearDown() { + protected function tearDown() + { } - protected function onNotSuccessfulTest(Exception $exception) { + protected function onNotSuccessfulTest(Exception $exception) + { // drops and reconnect to a redis server on uncaught exceptions RC::resetConnection(); + parent::onNotSuccessfulTest($exception); } /* Predis\ConnectionParameters */ - function testConnectionParametersDefaultValues() { - $params = new \Predis\ConnectionParameters(); + function testConnectionParametersDefaultValues() + { + $params = new Predis\ConnectionParameters(); $this->assertEquals('127.0.0.1', $params->host); $this->assertEquals(6379, $params->port); @@ -31,9 +37,10 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertNull($params->alias); } - function testConnectionParametersSetupValuesArray() { + function testConnectionParametersSetupValuesArray() + { $paramsArray = RC::getConnectionParametersArgumentsArray(); - $params = new \Predis\ConnectionParameters($paramsArray); + $params = new Predis\ConnectionParameters($paramsArray); $this->assertEquals($paramsArray['host'], $params->host); $this->assertEquals($paramsArray['port'], $params->port); @@ -44,10 +51,11 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals($paramsArray['alias'], $params->alias); } - function testConnectionParametersSetupValuesString() { + function testConnectionParametersSetupValuesString() + { $paramsArray = RC::getConnectionParametersArgumentsArray(); $paramsString = RC::getConnectionParametersArgumentsString($paramsArray); - $params = new \Predis\ConnectionParameters($paramsArray); + $params = new Predis\ConnectionParameters($paramsArray); $this->assertEquals($paramsArray['host'], $params->host); $this->assertEquals($paramsArray['port'], $params->port); @@ -58,34 +66,35 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals($paramsArray['alias'], $params->alias); } - /* Predis\Commands\Command and derivates */ - function testCommand_TestArguments() { + function testCommand_TestArguments() + { $cmdArgs = array('key1', 'key2', 'key3'); - $cmd = new \Predis\Commands\StringGetMultiple(); + $cmd = new Predis\Commands\StringGetMultiple(); $cmd->setArguments($cmdArgs); $this->assertEquals($cmdArgs[0], $cmd->getArgument(0)); $this->assertEquals($cmdArgs[1], $cmd->getArgument(1)); $this->assertEquals($cmdArgs[2], $cmd->getArgument(2)); - $cmd = new \Predis\Commands\ConnectionPing(); + $cmd = new Predis\Commands\ConnectionPing(); $this->assertNull($cmd->getArgument(0)); } - function testCommand_ParseResponse() { + function testCommand_ParseResponse() + { // default parser - $cmd = new \Predis\Commands\StringGet(); + $cmd = new Predis\Commands\StringGet(); $this->assertEquals('test', $cmd->parseResponse('test')); // overridden parser (boolean) - $cmd = new \Predis\Commands\KeyExists(); + $cmd = new Predis\Commands\KeyExists(); $this->assertTrue($cmd->parseResponse('1')); $this->assertFalse($cmd->parseResponse('0')); // overridden parser (boolean) - $cmd = new \Predis\Commands\ConnectionPing(); + $cmd = new Predis\Commands\ConnectionPing(); $this->assertTrue($cmd->parseResponse('PONG')); // overridden parser (complex) @@ -95,18 +104,20 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { /* Predis\Profiles\ServerProfile and derivates */ - function testServerProfile_GetSpecificVersions() { - $this->assertInstanceOf('\Predis\Profiles\ServerVersion12', \Predis\Profiles\ServerProfile::get('1.2')); - $this->assertInstanceOf('\Predis\Profiles\ServerVersion20', \Predis\Profiles\ServerProfile::get('2.0')); - $this->assertInstanceOf('\Predis\Profiles\ServerVersion22', \Predis\Profiles\ServerProfile::get('2.2')); - $this->assertInstanceOf('\Predis\Profiles\ServerVersionNext', \Predis\Profiles\ServerProfile::get('dev')); - $this->assertInstanceOf('\Predis\Profiles\ServerProfile', \Predis\Profiles\ServerProfile::get('default')); - $this->assertEquals(\Predis\Profiles\ServerProfile::get('default'), \Predis\Profiles\ServerProfile::getDefault()); + function testServerProfile_GetSpecificVersions() + { + $this->assertInstanceOf('\Predis\Profiles\ServerVersion12', Predis\Profiles\ServerProfile::get('1.2')); + $this->assertInstanceOf('\Predis\Profiles\ServerVersion20', Predis\Profiles\ServerProfile::get('2.0')); + $this->assertInstanceOf('\Predis\Profiles\ServerVersion22', Predis\Profiles\ServerProfile::get('2.2')); + $this->assertInstanceOf('\Predis\Profiles\ServerVersionNext', Predis\Profiles\ServerProfile::get('dev')); + $this->assertInstanceOf('\Predis\Profiles\ServerProfile', Predis\Profiles\ServerProfile::get('default')); + $this->assertEquals(Predis\Profiles\ServerProfile::get('default'), Predis\Profiles\ServerProfile::getDefault()); } - function testServerProfile_SupportedCommands() { - $profile_12 = \Predis\Profiles\ServerProfile::get('1.2'); - $profile_20 = \Predis\Profiles\ServerProfile::get('2.0'); + function testServerProfile_SupportedCommands() + { + $profile_12 = Predis\Profiles\ServerProfile::get('1.2'); + $profile_20 = Predis\Profiles\ServerProfile::get('2.0'); $this->assertTrue($profile_12->supportsCommand('info')); $this->assertTrue($profile_20->supportsCommand('info')); @@ -118,8 +129,9 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertFalse($profile_20->supportsCommand('watch')); } - function testServerProfile_CommandsCreation() { - $profile = \Predis\Profiles\ServerProfile::get('2.0'); + function testServerProfile_CommandsCreation() + { + $profile = Predis\Profiles\ServerProfile::get('2.0'); $cmdNoArgs = $profile->createCommand('info'); $this->assertInstanceOf('\Predis\Commands\ServerInfo', $cmdNoArgs); @@ -127,6 +139,7 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $args = array('key1', 'key2'); $cmdWithArgs = $profile->createCommand('mget', $args); + $this->assertInstanceOf('\Predis\Commands\StringGetMultiple', $cmdWithArgs); $this->assertEquals($args[0], $cmdWithArgs->getArgument()); // TODO: why? $this->assertEquals($args[0], $cmdWithArgs->getArgument(0)); @@ -141,8 +154,9 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { }); } - function testServerProfile_CommandsRegistration() { - $profile = \Predis\Profiles\ServerProfile::get('1.2'); + function testServerProfile_CommandsRegistration() + { + $profile = Predis\Profiles\ServerProfile::get('1.2'); $cmdId = 'multi'; $cmdClass = '\Predis\Commands\TransactionMulti'; @@ -164,21 +178,21 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals($uppercase, $lowercase); } - /* Predis\ResponseQueued */ - function testResponseQueued() { - $response = new \Predis\ResponseQueued(); + function testResponseQueued() + { + $response = new Predis\ResponseQueued(); $this->assertInstanceOf('\Predis\IReplyObject', $response); $this->assertEquals(\Predis\Protocol\Text\TextProtocol::QUEUED, (string)$response); } - /* Predis\ResponseError */ - function testResponseError() { + function testResponseError() + { $errorMessage = 'ERROR MESSAGE'; - $response = new \Predis\ResponseError($errorMessage); + $response = new Predis\ResponseError($errorMessage); $this->assertInstanceOf('\Predis\IReplyObject', $response); $this->assertInstanceOf('\Predis\IRedisServerError', $response); @@ -187,16 +201,17 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals($errorMessage, (string)$response); } - /* Predis\Network\StreamConnection */ - function testStreamConnection_StringCastReturnsIPAndPort() { - $connection = new \Predis\Network\StreamConnection(RC::getConnectionParameters()); + function testStreamConnection_StringCastReturnsIPAndPort() + { + $connection = new Predis\Network\StreamConnection(RC::getConnectionParameters()); $this->assertEquals(RC::SERVER_HOST . ':' . RC::SERVER_PORT, (string) $connection); } - function testStreamConnection_ConnectDisconnect() { - $connection = new \Predis\Network\StreamConnection(RC::getConnectionParameters()); + function testStreamConnection_ConnectDisconnect() + { + $connection = new Predis\Network\StreamConnection(RC::getConnectionParameters()); $this->assertFalse($connection->isConnected()); $connection->connect(); @@ -205,23 +220,27 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertFalse($connection->isConnected()); } - function testStreamConnection_WriteAndReadCommand() { - $cmd = \Predis\Profiles\ServerProfile::getDefault()->createCommand('ping'); - $connection = new \Predis\Network\StreamConnection(RC::getConnectionParameters()); + function testStreamConnection_WriteAndReadCommand() + { + $cmd = Predis\Profiles\ServerProfile::getDefault()->createCommand('ping'); + $connection = new Predis\Network\StreamConnection(RC::getConnectionParameters()); $connection->connect(); $connection->writeCommand($cmd); $this->assertTrue($connection->readResponse($cmd)); } - function testStreamConnection_WriteCommandAndCloseConnection() { - $cmd = \Predis\Profiles\ServerProfile::getDefault()->createCommand('quit'); - $connection = new \Predis\Network\StreamConnection(new \Predis\ConnectionParameters( + function testStreamConnection_WriteCommandAndCloseConnection() + { + $cmd = Predis\Profiles\ServerProfile::getDefault()->createCommand('quit'); + $connection = new Predis\Network\StreamConnection(new Predis\ConnectionParameters( RC::getConnectionArguments() + array('read_write_timeout' => 0.5) )); $connection->connect(); + $this->assertTrue($connection->isConnected()); + $connection->writeCommand($cmd); $connection->disconnect(); @@ -231,50 +250,59 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { }); } - function testStreamConnection_GetSocketOpensConnection() { - $connection = new \Predis\Network\StreamConnection(RC::getConnectionParameters()); + function testStreamConnection_GetSocketOpensConnection() + { + $connection = new Predis\Network\StreamConnection(RC::getConnectionParameters()); $this->assertFalse($connection->isConnected()); $this->assertInternalType('resource', $connection->getResource()); $this->assertTrue($connection->isConnected()); } - function testStreamConnection_LazyConnect() { - $cmd = \Predis\Profiles\ServerProfile::getDefault()->createCommand('ping'); - $connection = new \Predis\Network\StreamConnection(RC::getConnectionParameters()); + function testStreamConnection_LazyConnect() + { + $cmd = Predis\Profiles\ServerProfile::getDefault()->createCommand('ping'); + $connection = new Predis\Network\StreamConnection(RC::getConnectionParameters()); $this->assertFalse($connection->isConnected()); + $connection->writeCommand($cmd); + $this->assertTrue($connection->isConnected()); $this->assertTrue($connection->readResponse($cmd)); } - function testStreamConnection_Alias() { - $connection1 = new \Predis\Network\StreamConnection(RC::getConnectionParameters()); + function testStreamConnection_Alias() + { + $connection1 = new Predis\Network\StreamConnection(RC::getConnectionParameters()); $this->assertNull($connection1->getParameters()->alias); $args = array_merge(RC::getConnectionArguments(), array('alias' => 'servername')); - $connection2 = new \Predis\Network\StreamConnection(new \Predis\ConnectionParameters($args)); + $connection2 = new Predis\Network\StreamConnection(new Predis\ConnectionParameters($args)); + $this->assertEquals('servername', $connection2->getParameters()->alias); } - function testStreamConnection_ConnectionTimeout() { + function testStreamConnection_ConnectionTimeout() + { $timeout = 3; - $args = array('host' => '1.0.0.1', 'connection_timeout' => $timeout); - $connection = new \Predis\Network\StreamConnection(new \Predis\ConnectionParameters($args)); + $args = array('host' => '1.0.0.1', 'connection_timeout' => $timeout); + $connection = new Predis\Network\StreamConnection(new Predis\ConnectionParameters($args)); $start = time(); RC::testForCommunicationException($this, null, function() use($connection) { $connection->connect(); }); + $this->assertEquals((float)(time() - $start), $timeout, '', 1); } - function testStreamConnection_ReadTimeout() { + function testStreamConnection_ReadTimeout() + { $timeout = 1; - $args = array_merge(RC::getConnectionArguments(), array('read_write_timeout' => $timeout)); - $cmdFake = \Predis\Profiles\ServerProfile::getDefault()->createCommand('ping'); - $connection = new \Predis\Network\StreamConnection(new \Predis\ConnectionParameters($args)); + $args = array_merge(RC::getConnectionArguments(), array('read_write_timeout' => $timeout)); + $cmdFake = Predis\Profiles\ServerProfile::getDefault()->createCommand('ping'); + $connection = new Predis\Network\StreamConnection(new Predis\ConnectionParameters($args)); $expectedMessage = 'Error while reading line from the server'; $start = time(); @@ -284,41 +312,42 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals((float)(time() - $start), $timeout, '', 1); } - /* Predis\Protocol\TextResponseReader */ - function testResponseReader_OptionIterableMultiBulkReplies() { + function testResponseReader_OptionIterableMultiBulkReplies() + { $protocol = new Predis\Protocol\Text\ComposableTextProtocol(); $reader = $protocol->getReader(); - $connection = new \Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol); + $connection = new Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol); $reader->setHandler( - \Predis\Protocol\Text\TextProtocol::PREFIX_MULTI_BULK, - new \Predis\Protocol\Text\ResponseMultiBulkHandler() + Predis\Protocol\Text\TextProtocol::PREFIX_MULTI_BULK, + new Predis\Protocol\Text\ResponseMultiBulkHandler() ); $connection->writeBytes("KEYS *\r\n"); $this->assertInternalType('array', $reader->read($connection)); $reader->setHandler( - \Predis\Protocol\Text\TextProtocol::PREFIX_MULTI_BULK, - new \Predis\Protocol\Text\ResponseMultiBulkStreamHandler() + Predis\Protocol\Text\TextProtocol::PREFIX_MULTI_BULK, + new Predis\Protocol\Text\ResponseMultiBulkStreamHandler() ); $connection->writeBytes("KEYS *\r\n"); $this->assertInstanceOf('\Iterator', $reader->read($connection)); } - function testResponseReader_OptionExceptionOnError() { + function testResponseReader_OptionExceptionOnError() + { $protocol = new Predis\Protocol\Text\ComposableTextProtocol(); $reader = $protocol->getReader(); - $connection = new \Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol); + $connection = new Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol); $rawCmdUnexpected = "*3\r\n$5\r\nLPUSH\r\n$3\r\nkey\r\n$5\r\nvalue\r\n"; $connection->writeBytes("*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n"); $reader->read($connection); $reader->setHandler( - \Predis\Protocol\Text\TextProtocol::PREFIX_ERROR, - new \Predis\Protocol\Text\ResponseErrorSilentHandler() + Predis\Protocol\Text\TextProtocol::PREFIX_ERROR, + new Predis\Protocol\Text\ResponseErrorSilentHandler() ); $connection->writeBytes($rawCmdUnexpected); $errorReply = $reader->read($connection); @@ -326,8 +355,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(RC::EXCEPTION_WRONG_TYPE, $errorReply->getMessage()); $reader->setHandler( - \Predis\Protocol\Text\TextProtocol::PREFIX_ERROR, - new \Predis\Protocol\Text\ResponseErrorHandler() + Predis\Protocol\Text\TextProtocol::PREFIX_ERROR, + new Predis\Protocol\Text\ResponseErrorHandler() ); RC::testForServerException($this, RC::EXCEPTION_WRONG_TYPE, function() use ($connection, $rawCmdUnexpected) { @@ -337,10 +366,11 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { }); } - function testResponseReader_EmptyBulkResponse() { - $protocol = new \Predis\Protocol\Text\ComposableTextProtocol(); - $connection = new \Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol); - $client = new \Predis\Client($connection); + function testResponseReader_EmptyBulkResponse() + { + $protocol = new Predis\Protocol\Text\ComposableTextProtocol(); + $connection = new Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol); + $client = new Predis\Client($connection); $this->assertTrue($client->set('foo', '')); $this->assertEquals('', $client->get('foo')); @@ -349,17 +379,19 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { /* Client initialization */ - function testClientInitialization_SingleConnectionParameters() { + function testClientInitialization_SingleConnectionParameters() + { $params1 = array_merge(RC::getConnectionArguments(), array( 'connection_timeout' => 10, 'read_write_timeout' => 30, 'alias' => 'connection_alias', )); $params2 = RC::getConnectionParametersArgumentsString($params1); - $params3 = new \Predis\ConnectionParameters($params1); - $params4 = new \Predis\Network\StreamConnection($params3); + $params3 = new Predis\ConnectionParameters($params1); + $params4 = new Predis\Network\StreamConnection($params3); + foreach (array($params1, $params2, $params3, $params4) as $params) { - $client = new \Predis\Client($params); + $client = new Predis\Client($params); $parameters = $client->getConnection()->getParameters(); $this->assertEquals($params1['host'], $parameters->host); $this->assertEquals($params1['port'], $parameters->port); @@ -370,16 +402,18 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { } } - function testClientInitialization_ClusterConnectionParameters() { + function testClientInitialization_ClusterConnectionParameters() + { $params1 = array_merge(RC::getConnectionArguments(), array( 'connection_timeout' => 10, 'read_write_timeout' => 30, )); $params2 = RC::getConnectionParametersArgumentsString($params1); - $params3 = new \Predis\ConnectionParameters($params1); - $params4 = new \Predis\Network\StreamConnection($params3); + $params3 = new Predis\ConnectionParameters($params1); + $params4 = new Predis\Network\StreamConnection($params3); + + $client1 = new Predis\Client(array($params1, $params2, $params3, $params4)); - $client1 = new \Predis\Client(array($params1, $params2, $params3, $params4)); foreach ($client1->getConnection() as $connection) { $parameters = $connection->getParameters(); $this->assertEquals($params1['host'], $parameters->host); @@ -390,14 +424,14 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { } $connectionCluster = $client1->getConnection(); - $client2 = new \Predis\Client($connectionCluster); + $client2 = new Predis\Client($connectionCluster); $this->assertSame($connectionCluster, $client2->getConnection()); } - /* Client + PipelineContext */ - function testPipelineContext_Simple() { + function testPipelineContext_Simple() + { $client = RC::getConnection(); $client->flushdb(); @@ -421,7 +455,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('barbar', $replies[3][2]); } - function testPipelineContext_FluentInterface() { + function testPipelineContext_FluentInterface() + { $client = RC::getConnection(); $client->flushdb(); @@ -430,7 +465,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('bar', $replies[2]); } - function testPipelineContext_CallableAnonymousBlock() { + function testPipelineContext_CallableAnonymousBlock() + { $client = RC::getConnection(); $client->flushdb(); @@ -444,7 +480,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('bar', $replies[2]); } - function testPipelineContext_ClientExceptionInCallableBlock() { + function testPipelineContext_ClientExceptionInCallableBlock() + { $client = RC::getConnection(); $client->flushdb(); @@ -452,13 +489,15 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $client->pipeline(function($pipe) { $pipe->ping(); $pipe->set('foo', 'bar'); - throw new \Predis\ClientException("TEST"); + throw new Predis\ClientException("TEST"); }); }); + $this->assertFalse($client->exists('foo')); } - function testPipelineContext_ServerExceptionInCallableBlock() { + function testPipelineContext_ServerExceptionInCallableBlock() + { $client = RC::createConnection(array('throw_errors' => false)); $client->flushdb(); @@ -474,7 +513,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertTrue($client->exists('hoge')); } - function testPipelineContext_Flush() { + function testPipelineContext_Flush() + { $client = RC::getConnection(); $client->flushdb(); @@ -490,10 +530,10 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('piyo', $replies[3][1]); } - /* Predis\Client + Predis\MultiExecContext */ - function testMultiExecContext_Simple() { + function testMultiExecContext_Simple() + { $client = RC::getConnection(); $client->flushdb(); @@ -517,7 +557,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('barbar', $replies[3][2]); } - function testMultiExecContext_FluentInterface() { + function testMultiExecContext_FluentInterface() + { $client = RC::getConnection(); $client->flushdb(); @@ -526,7 +567,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('bar', $replies[2]); } - function testMultiExecContext_CallableAnonymousBlock() { + function testMultiExecContext_CallableAnonymousBlock() + { $client = RC::getConnection(); $client->flushdb(); @@ -543,12 +585,14 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { /** * @expectedException Predis\ClientException */ - function testMultiExecContext_CannotMixFluentInterfaceAndAnonymousBlock() { + function testMultiExecContext_CannotMixFluentInterfaceAndAnonymousBlock() + { $emptyBlock = function($tx) { }; $tx = RC::getConnection()->multiExec()->get('foo')->execute($emptyBlock); } - function testMultiExecContext_EmptyCallableBlock() { + function testMultiExecContext_EmptyCallableBlock() + { $client = RC::getConnection(); $client->flushdb(); @@ -566,7 +610,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(0, count($replies)); } - function testMultiExecContext_ClientExceptionInCallableBlock() { + function testMultiExecContext_ClientExceptionInCallableBlock() + { $client = RC::getConnection(); $client->flushdb(); @@ -574,13 +619,15 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $client->multiExec(function($multi) { $multi->ping(); $multi->set('foo', 'bar'); - throw new \Predis\ClientException("TEST"); + throw new Predis\ClientException("TEST"); }); }); + $this->assertFalse($client->exists('foo')); } - function testMultiExecContext_ServerExceptionInCallableBlock() { + function testMultiExecContext_ServerExceptionInCallableBlock() + { $client = RC::createConnection(array('throw_errors' => false)); $client->flushdb(); @@ -596,7 +643,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertTrue($client->exists('hoge')); } - function testMultiExecContext_Discard() { + function testMultiExecContext_Discard() + { $client = RC::getConnection(); $client->flushdb(); @@ -611,7 +659,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertTrue($client->exists('hoge')); } - function testMultiExecContext_DiscardEmpty() { + function testMultiExecContext_DiscardEmpty() + { $client = RC::getConnection(); $client->flushdb(); @@ -622,7 +671,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(0, count($replies)); } - function testMultiExecContext_Watch() { + function testMultiExecContext_Watch() + { $client1 = RC::getConnection(); $client2 = RC::getConnection(true); $client1->flushdb(); @@ -642,7 +692,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('client2', $client1->get('sentinel')); } - function testMultiExecContext_CheckAndSet() { + function testMultiExecContext_CheckAndSet() + { $client = RC::getConnection(); $client->flushdb(); $client->set('foo', 'bar'); @@ -669,7 +720,8 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(array(true, array('bar', 'bar')), $replies); } - function testMultiExecContext_RetryOnServerAbort() { + function testMultiExecContext_RetryOnServerAbort() + { $client1 = RC::getConnection(); $client2 = RC::getConnection(true); $client1->flushdb(); @@ -721,13 +773,15 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { /** * @expectedException InvalidArgumentException */ - function testMultiExecContext_RetryNotAvailableWithoutBlock() { + function testMultiExecContext_RetryNotAvailableWithoutBlock() + { $options = array('watch' => 'foo', 'retry' => 1); $tx = RC::getConnection()->multiExec($options); $tx->multi()->get('foo')->exec(); } - function testMultiExecContext_CheckAndSet_Discard() { + function testMultiExecContext_CheckAndSet_Discard() + { $client = RC::getConnection(); $client->flushdb(); @@ -765,4 +819,3 @@ class ClientFeaturesTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(array(array('hijacked!', null)), $replies); } } -?> diff --git a/test/PredisShared.php b/test/PredisShared.php index ed6f3250..1823187e 100644 --- a/test/PredisShared.php +++ b/test/PredisShared.php @@ -9,12 +9,14 @@ if (!file_exists(__DIR__.'/enable.tests')) { } if (!function_exists('array_union')) { - function array_union(Array $a, Array $b) { + function array_union(Array $a, Array $b) + { return array_merge($a, array_diff($b, $a)); } } -class RC { +class RC +{ const SERVER_VERSION = '2.2'; const SERVER_HOST = '127.0.0.1'; const SERVER_PORT = 6379; @@ -35,44 +37,55 @@ class RC { private static $_connection; - public static function getConnectionArguments(Array $additional = array()) { + public static function getConnectionArguments(Array $additional = array()) + { return array_merge(array('host' => RC::SERVER_HOST, 'port' => RC::SERVER_PORT), $additional); } - public static function getConnectionParameters(Array $additional = array()) { + public static function getConnectionParameters(Array $additional = array()) + { return new Predis\ConnectionParameters(self::getConnectionArguments($additional)); } - public static function createConnection(Array $additional = array()) { + public static function createConnection(Array $additional = array()) + { $serverProfile = Predis\Profiles\ServerProfile::get(self::SERVER_VERSION); + $connection = new Predis\Client(RC::getConnectionArguments($additional), $serverProfile); $connection->connect(); $connection->select(RC::DEFAULT_DATABASE); + return $connection; } - public static function getConnection($new = false) { + public static function getConnection($new = false) + { if ($new == true) { return self::createConnection(); } + if (self::$_connection === null || !self::$_connection->isConnected()) { self::$_connection = self::createConnection(); } + return self::$_connection; } - public static function resetConnection() { + public static function resetConnection() + { if (self::$_connection !== null && self::$_connection->isConnected()) { self::$_connection->disconnect(); self::$_connection = self::createConnection(); } } - public static function helperForBlockingPops($op) { + public static function helperForBlockingPops($op) + { // TODO: I admit that this helper is kinda lame and it does not run // in a separate process to properly test BLPOP/BRPOP $redisUri = sprintf('tcp://%s:%d/?database=%d', RC::SERVER_HOST, RC::SERVER_PORT, RC::DEFAULT_DATABASE); $handle = popen('php', 'w'); + fwrite($handle, "rpush('{$op}3', 'c'); \$redis->rpush('{$op}1', 'd'); ?>"); + pclose($handle); } - public static function getArrayOfNumbers() { + public static function getArrayOfNumbers() + { return array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } - public static function getKeyValueArray() { + public static function getKeyValueArray() + { return array( 'foo' => 'bar', 'hoge' => 'piyo', @@ -96,7 +112,8 @@ class RC { ); } - public static function getNamespacedKeyValueArray() { + public static function getNamespacedKeyValueArray() + { return array( 'metavar:foo' => 'bar', 'metavar:hoge' => 'piyo', @@ -104,120 +121,154 @@ class RC { ); } - public static function getZSetArray() { - return array( - 'a' => -10, 'b' => 0, 'c' => 10, 'd' => 20, 'e' => 20, 'f' => 30 - ); + public static function getZSetArray() + { + return array('a' => -10, 'b' => 0, 'c' => 10, 'd' => 20, 'e' => 20, 'f' => 30); } - public static function sameValuesInArrays($arrayA, $arrayB) { + public static function sameValuesInArrays($arrayA, $arrayB) + { if (count($arrayA) != count($arrayB)) { return false; } + return count(array_diff($arrayA, $arrayB)) == 0; } - public static function testForServerException($testcaseInstance, $expectedMessage, $wrapFunction) { + public static function testForServerException($testcaseInstance, $expectedMessage, $wrapFunction) + { $thrownException = null; + try { $wrapFunction($testcaseInstance); } catch (Predis\ServerException $exception) { $thrownException = $exception; } + $testcaseInstance->assertInstanceOf('Predis\ServerException', $thrownException); + if (isset($expectedMessage)) { $testcaseInstance->assertEquals($expectedMessage, $thrownException->getMessage()); } } - public static function testForClientException($testcaseInstance, $expectedMessage, $wrapFunction) { + public static function testForClientException($testcaseInstance, $expectedMessage, $wrapFunction) + { $thrownException = null; + try { $wrapFunction($testcaseInstance); } catch (Predis\ClientException $exception) { $thrownException = $exception; } + $testcaseInstance->assertInstanceOf('Predis\ClientException', $thrownException); + if (isset($expectedMessage)) { $testcaseInstance->assertEquals($expectedMessage, $thrownException->getMessage()); } } - public static function testForCommunicationException($testcaseInstance, $expectedMessage, $wrapFunction) { + public static function testForCommunicationException($testcaseInstance, $expectedMessage, $wrapFunction) + { $thrownException = null; + try { $wrapFunction($testcaseInstance); } catch (Predis\CommunicationException $exception) { $thrownException = $exception; } + $testcaseInstance->assertInstanceOf('Predis\CommunicationException', $thrownException); + if (isset($expectedMessage)) { $testcaseInstance->assertEquals($expectedMessage, $thrownException->getMessage()); } } - public static function testForAbortedMultiExecException($testcaseInstance, $wrapFunction) { + public static function testForAbortedMultiExecException($testcaseInstance, $wrapFunction) + { $thrownException = null; + try { $wrapFunction($testcaseInstance); } catch (Predis\Transaction\AbortedMultiExecException $exception) { $thrownException = $exception; } + $testcaseInstance->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $thrownException); } - public static function pushTailAndReturn(Predis\Client $client, $keyName, Array $values, $wipeOut = 0) { + public static function pushTailAndReturn(Predis\Client $client, $keyName, Array $values, $wipeOut = 0) + { if ($wipeOut == true) { $client->del($keyName); } + foreach ($values as $value) { $client->rpush($keyName, $value); } + return $values; } - public static function setAddAndReturn(Predis\Client $client, $keyName, Array $values, $wipeOut = 0) { + public static function setAddAndReturn(Predis\Client $client, $keyName, Array $values, $wipeOut = 0) + { if ($wipeOut == true) { $client->del($keyName); } + foreach ($values as $value) { $client->sadd($keyName, $value); } + return $values; } - public static function zsetAddAndReturn(Predis\Client $client, $keyName, Array $values, $wipeOut = 0) { + public static function zsetAddAndReturn(Predis\Client $client, $keyName, Array $values, $wipeOut = 0) + { // $values: array(SCORE => VALUE, ...); if ($wipeOut == true) { $client->del($keyName); } + foreach ($values as $value => $score) { $client->zadd($keyName, $score, $value); } + return $values; } - public static function getConnectionParametersArgumentsArray() { + public static function getConnectionParametersArgumentsArray() + { return array( - 'host' => '10.0.0.1', 'port' => 6380, 'connection_timeout' => 10, 'read_write_timeout' => 30, - 'database' => 5, 'password' => 'dbpassword', 'alias' => 'connection_alias' + 'host' => '10.0.0.1', + 'port' => 6380, + 'connection_timeout' => 10, + 'read_write_timeout' => 30, + 'database' => 5, + 'password' => 'dbpassword', + 'alias' => 'connection_alias', ); } - public static function getConnectionParametersArgumentsString($arguments = null) { + public static function getConnectionParametersArgumentsString($arguments = null) + { // TODO: must be improved $args = $arguments ?: RC::getConnectionParametersArgumentsArray(); $paramsString = "tcp://{$args['host']}:{$args['port']}/?"; + unset($args['host']); unset($args['port']); + foreach($args as $k => $v) { $paramsString .= "$k=$v&"; } + return $paramsString; } } -?> diff --git a/test/RedisCommandsTest.php b/test/RedisCommandsTest.php index ec6548da..d28cbc35 100644 --- a/test/RedisCommandsTest.php +++ b/test/RedisCommandsTest.php @@ -1,6 +1,7 @@ redis = RC::getConnection(); $this->redis->flushdb(); } - protected function tearDown() { + protected function tearDown() + { } - protected function onNotSuccessfulTest(Exception $exception) { + protected function onNotSuccessfulTest(Exception $exception) + { // drops and reconnect to a redis server on uncaught exceptions RC::resetConnection(); + parent::onNotSuccessfulTest($exception); } - /* miscellaneous commands */ - function testPing() { + function testPing() + { $this->assertTrue($this->redis->ping()); } - function testEcho() { + function testEcho() + { $string = 'This is an echo test!'; $this->assertEquals($string, $this->redis->echo($string)); } - function testQuit() { + function testQuit() + { $this->redis->quit(); $this->assertFalse($this->redis->isConnected()); } - function testMultiExec() { + function testMultiExec() + { // NOTE: due to a limitation in the current implementation of Predis\Client, // the replies returned by Predis\Commands\Exec are not parsed by their // respective Predis\Commands\Command::parseResponse methods. If you // need that kind of behaviour, you should use an instance of // Predis\MultiExecBlock. + $this->assertTrue($this->redis->multi()); $this->assertInstanceOf('Predis\ResponseQueued', $this->redis->ping()); $this->assertInstanceOf('Predis\ResponseQueued', $this->redis->echo('hello')); @@ -62,7 +71,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testDiscard() { + function testDiscard() + { $this->assertTrue($this->redis->multi()); $this->assertInstanceOf('Predis\ResponseQueued', $this->redis->set('foo', 'bar')); $this->assertInstanceOf('Predis\ResponseQueued', $this->redis->set('hoge', 'piyo')); @@ -79,12 +89,14 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { /* commands operating on string values */ - function testSet() { + function testSet() + { $this->assertTrue($this->redis->set('foo', 'bar')); $this->assertEquals('bar', $this->redis->get('foo')); } - function testGet() { + function testGet() + { $this->redis->set('foo', 'bar'); $this->assertEquals('bar', $this->redis->get('foo')); @@ -100,14 +112,16 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testExists() { + function testExists() + { $this->redis->set('foo', 'bar'); $this->assertTrue($this->redis->exists('foo')); $this->assertFalse($this->redis->exists('key_does_not_exist')); } - function testSetPreserve() { + function testSetPreserve() + { $multi = RC::getKeyValueArray(); $this->assertTrue($this->redis->setnx('foo', 'bar')); @@ -115,7 +129,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('bar', $this->redis->get('foo')); } - function testMultipleSetAndGet() { + function testMultipleSetAndGet() + { $multi = RC::getKeyValueArray(); // key=>value pairs via array instance @@ -128,7 +143,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(array(1, 2, 3), $this->redis->mget('a', 'b', 'c')); } - function testSetMultiplePreserve() { + function testSetMultiplePreserve() + { $multi = RC::getKeyValueArray(); $newpair = array('hogehoge' => 'piyopiyo'); $hijacked = array('foo' => 'baz', 'hoge' => 'fuga'); @@ -154,13 +170,15 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { ); } - function testGetSet() { + function testGetSet() + { $this->assertNull($this->redis->getset('foo', 'bar')); $this->assertEquals('bar', $this->redis->getset('foo', 'barbar')); $this->assertEquals('barbar', $this->redis->getset('foo', 'baz')); } - function testIncrementAndIncrementBy() { + function testIncrementAndIncrementBy() + { // test subsequent increment commands $this->assertEquals(1, $this->redis->incr('foo')); $this->assertEquals(2, $this->redis->incr('foo')); @@ -171,7 +189,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(-100, $this->redis->incrby('foo', -110)); } - function testDecrementAndDecrementBy() { + function testDecrementAndDecrementBy() + { // test subsequent decrement commands $this->assertEquals(-1, $this->redis->decr('foo')); $this->assertEquals(-2, $this->redis->decr('foo')); @@ -182,14 +201,16 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(100, $this->redis->decrby('foo', -110)); } - function testDelete() { + function testDelete() + { $this->redis->set('foo', 'bar'); $this->assertEquals(1, $this->redis->del('foo')); $this->assertFalse($this->redis->exists('foo')); $this->assertEquals(0, $this->redis->del('foo')); } - function testType() { + function testType() + { $this->assertEquals('none', $this->redis->type('fooDoesNotExist')); $this->redis->set('fooString', 'bar'); @@ -208,7 +229,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals('hash', $this->redis->type('fooHash')); } - function testAppend() { + function testAppend() + { $this->redis->set('foo', 'bar'); $this->assertEquals(5, $this->redis->append('foo', '__')); $this->assertEquals(8, $this->redis->append('foo', 'bar')); @@ -223,7 +245,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetRange() { + function testSetRange() + { $this->assertEquals(6, $this->redis->setrange('var', 0, 'foobar')); $this->assertEquals('foobar', $this->redis->get('var')); $this->assertEquals(6, $this->redis->setrange('var', 3, 'foo')); @@ -245,7 +268,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSubstr() { + function testSubstr() + { $this->redis->set('var', 'foobar'); $this->assertEquals('foo', $this->redis->substr('var', 0, 2)); $this->assertEquals('bar', $this->redis->substr('var', 3, 5)); @@ -262,7 +286,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testStrlen() { + function testStrlen() + { $this->redis->set('var', 'foobar'); $this->assertEquals(6, $this->redis->strlen('var')); $this->assertEquals(9, $this->redis->append('var', '___')); @@ -274,7 +299,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetBit() { + function testSetBit() + { $this->assertEquals(0, $this->redis->setbit('binary', 31, 1)); $this->assertEquals(0, $this->redis->setbit('binary', 0, 1)); $this->assertEquals(4, $this->redis->strlen('binary')); @@ -306,7 +332,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testGetBit() { + function testGetBit() + { $this->redis->set('binary', "\x80\x00\00\x01"); $this->assertEquals(1, $this->redis->getbit('binary', 0)); @@ -328,11 +355,10 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - - /* commands operating on the key space */ - function testKeys() { + function testKeys() + { $keyValsNs = RC::getNamespacedKeyValueArray(); $keyValsOthers = array('aaa' => 1, 'aba' => 2, 'aca' => 3); $allKeyVals = array_merge($keyValsNs, $keyValsOthers); @@ -351,7 +377,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(array(), array_diff(array_keys($keyValsOthers), $keysFromRedis)); } - function testRandomKey() { + function testRandomKey() + { $keyvals = RC::getKeyValueArray(); $this->assertNull($this->redis->randomkey()); @@ -360,7 +387,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertTrue(in_array($this->redis->randomkey(), array_keys($keyvals))); } - function testRename() { + function testRename() + { $this->redis->mset(array('foo' => 'bar', 'foofoo' => 'barbar')); // rename existing keys @@ -374,7 +402,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testRenamePreserve() { + function testRenamePreserve() + { $this->redis->mset(array('foo' => 'bar', 'hoge' => 'piyo', 'hogehoge' => 'piyopiyo')); $this->assertTrue($this->redis->renamenx('foo', 'foofoo')); @@ -390,7 +419,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testExpirationAndTTL() { + function testExpirationAndTTL() + { $this->redis->set('foo', 'bar'); // check for key expiration @@ -414,7 +444,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(-1, $this->redis->ttl('foo')); } - function testPersist() { + function testPersist() + { $this->redis->set('foo', 'bar'); $this->assertTrue($this->redis->expire('foo', 1)); @@ -426,7 +457,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertFalse($this->redis->persist('foobar')); } - function testSetExpire() { + function testSetExpire() + { $this->assertTrue($this->redis->setex('foo', 10, 'bar')); $this->assertTrue($this->redis->exists('foo')); $this->assertEquals(10, $this->redis->ttl('foo')); @@ -447,17 +479,18 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testDatabaseSize() { + function testDatabaseSize() + { // TODO: is this really OK? $this->assertEquals(0, $this->redis->dbsize()); $this->redis->mset(RC::getKeyValueArray()); $this->assertGreaterThan(0, $this->redis->dbsize()); } - /* commands operating on lists */ - function testPushTail() { + function testPushTail() + { // NOTE: List push operations return the list length since Redis commit 520b5a3 $this->assertEquals(1, $this->redis->rpush('metavars', 'foo')); $this->assertTrue($this->redis->exists('metavars')); @@ -470,7 +503,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testPushTailX() { + function testPushTailX() + { $this->assertEquals(0, $this->redis->rpushx('numbers', 1)); $this->assertEquals(1, $this->redis->rpush('numbers', 2)); $this->assertEquals(2, $this->redis->rpushx('numbers', 3)); @@ -484,7 +518,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testPushHead() { + function testPushHead() + { // NOTE: List push operations return the list length since Redis commit 520b5a3 $this->assertEquals(1, $this->redis->lpush('metavars', 'foo')); $this->assertTrue($this->redis->exists('metavars')); @@ -497,7 +532,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testPushHeadX() { + function testPushHeadX() + { $this->assertEquals(0, $this->redis->lpushx('numbers', 1)); $this->assertEquals(1, $this->redis->lpush('numbers', 2)); $this->assertEquals(2, $this->redis->lpushx('numbers', 3)); @@ -511,7 +547,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListLength() { + function testListLength() + { $this->assertEquals(1, $this->redis->rpush('metavars', 'foo')); $this->assertEquals(2, $this->redis->rpush('metavars', 'hoge')); $this->assertEquals(2, $this->redis->llen('metavars')); @@ -525,7 +562,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListRange() { + function testListRange() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', RC::getArrayOfNumbers()); $this->assertEquals( @@ -577,7 +615,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListTrim() { + function testListTrim() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', RC::getArrayOfNumbers()); $this->assertTrue($this->redis->ltrim('numbers', 0, 2)); $this->assertEquals( @@ -619,7 +658,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListIndex() { + function testListIndex() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', RC::getArrayOfNumbers()); $this->assertEquals(0, $this->redis->lindex('numbers', 0)); @@ -638,7 +678,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListSet() { + function testListSet() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', RC::getArrayOfNumbers()); $this->assertTrue($this->redis->lset('numbers', 5, -5)); @@ -654,7 +695,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListRemove() { + function testListRemove() + { $mixed = array(0, '_', 2, '_', 4, '_', 6, '_'); RC::pushTailAndReturn($this->redis, 'mixed', $mixed); @@ -681,7 +723,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListPopFirst() { + function testListPopFirst() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', array(0, 1, 2, 3, 4)); $this->assertEquals(0, $this->redis->lpop('numbers')); @@ -704,7 +747,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListPopLast() { + function testListPopLast() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', array(0, 1, 2, 3, 4)); $this->assertEquals(4, $this->redis->rpop('numbers')); @@ -727,7 +771,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListPopLastPushHead() { + function testListPopLastPushHead() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', array(0, 1, 2)); $this->assertEquals(0, $this->redis->llen('temporary')); $this->assertEquals(2, $this->redis->rpoplpush('numbers', 'temporary')); @@ -757,7 +802,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListBlockingPopFirst() { + function testListBlockingPopFirst() + { // TODO: this test does not cover all the aspects of BLPOP/BRPOP as it // does not run with a concurrent client pushing items on lists. RC::helperForBlockingPops('blpop'); @@ -784,7 +830,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals((float)(time() - $start), 2, '', 1); } - function testListBlockingPopLast() { + function testListBlockingPopLast() + { // TODO: this test does not cover all the aspects of BLPOP/BRPOP as it // does not run with a concurrent client pushing items on lists. RC::helperForBlockingPops('brpop'); @@ -811,7 +858,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals((float)(time() - $start), 2, '', 1); } - function testListBlockingPopLastPushHead() { + function testListBlockingPopLastPushHead() + { // TODO: this test does not cover all the aspects of BLPOP/BRPOP as it // does not run with a concurrent client pushing items on lists. $numbers = RC::pushTailAndReturn($this->redis, 'numbers', array(1, 2, 3)); @@ -836,7 +884,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testListInsert() { + function testListInsert() + { $numbers = RC::pushTailAndReturn($this->redis, 'numbers', RC::getArrayOfNumbers()); $this->assertEquals(11, $this->redis->linsert('numbers', 'before', 0, -2)); @@ -852,10 +901,10 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - /* commands operating on sets */ - function testSetAdd() { + function testSetAdd() + { $this->assertTrue($this->redis->sadd('set', 0)); $this->assertTrue($this->redis->sadd('set', 1)); $this->assertFalse($this->redis->sadd('set', 0)); @@ -866,7 +915,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetRemove() { + function testSetRemove() + { $set = RC::setAddAndReturn($this->redis, 'set', array(0, 1, 2, 3, 4)); $this->assertTrue($this->redis->srem('set', 0)); @@ -879,7 +929,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetPop() { + function testSetPop() + { $set = RC::setAddAndReturn($this->redis, 'set', array(0, 1, 2, 3, 4)); $this->assertTrue(in_array($this->redis->spop('set'), $set)); @@ -892,7 +943,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetMove() { + function testSetMove() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(5, 6, 7, 8, 9, 10)); @@ -913,7 +965,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetCardinality() { + function testSetCardinality() + { RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5)); $this->assertEquals(6, $this->redis->scard('setA')); @@ -933,7 +986,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetIsMember() { + function testSetIsMember() + { RC::setAddAndReturn($this->redis, 'set', array(0, 1, 2, 3, 4, 5)); $this->assertTrue($this->redis->sismember('set', 3)); @@ -948,7 +1002,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetMembers() { + function testSetMembers() + { $set = RC::setAddAndReturn($this->redis, 'set', array(0, 1, 2, 3, 4, 5, 6)); $this->assertTrue(RC::sameValuesInArrays($set, $this->redis->smembers('set'))); @@ -962,7 +1017,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetIntersection() { + function testSetIntersection() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5, 6)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(1, 3, 4, 6, 9, 10)); @@ -988,7 +1044,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetIntersectionStore() { + function testSetIntersectionStore() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5, 6)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(1, 3, 4, 6, 9, 10)); @@ -1023,7 +1080,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetUnion() { + function testSetUnion() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5, 6)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(1, 3, 4, 6, 9, 10)); @@ -1052,7 +1110,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetUnionStore() { + function testSetUnionStore() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5, 6)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(1, 3, 4, 6, 9, 10)); @@ -1089,7 +1148,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetDifference() { + function testSetDifference() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5, 6)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(1, 3, 4, 6, 9, 10)); @@ -1118,7 +1178,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testSetDifferenceStore() { + function testSetDifferenceStore() + { $setA = RC::setAddAndReturn($this->redis, 'setA', array(0, 1, 2, 3, 4, 5, 6)); $setB = RC::setAddAndReturn($this->redis, 'setB', array(1, 3, 4, 6, 9, 10)); @@ -1152,7 +1213,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testRandomMember() { + function testRandomMember() + { $set = RC::setAddAndReturn($this->redis, 'set', array(0, 1, 2, 3, 4, 5, 6)); $this->assertTrue(in_array($this->redis->srandmember('set'), $set)); @@ -1166,10 +1228,10 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - /* commands operating on sorted sets */ - function testZsetAdd() { + function testZsetAdd() + { $this->assertTrue($this->redis->zadd('zset', 0, 'a')); $this->assertTrue($this->redis->zadd('zset', 1, 'b')); @@ -1188,7 +1250,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetIncrementBy() { + function testZsetIncrementBy() + { $this->assertEquals(1, $this->redis->zincrby('zsetDoesNotExist', 1, 'foo')); $this->assertEquals('zset', $this->redis->type('zsetDoesNotExist')); @@ -1208,7 +1271,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetRemove() { + function testZsetRemove() + { RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertTrue($this->redis->zrem('zset', 'a')); @@ -1220,7 +1284,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetRange() { + function testZsetRange() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals( @@ -1284,7 +1349,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetReverseRange() { + function testZsetReverseRange() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals( @@ -1343,7 +1409,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetRangeByScore() { + function testZsetRangeByScore() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals( @@ -1402,7 +1469,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetReverseRangeByScore() { + function testZsetReverseRangeByScore() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals( @@ -1461,7 +1529,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetUnionStore() { + function testZsetUnionStore() + { $zsetA = RC::zsetAddAndReturn($this->redis, 'zseta', array('a' => 1, 'b' => 2, 'c' => 3)); $zsetB = RC::zsetAddAndReturn($this->redis, 'zsetb', array('b' => 1, 'c' => 2, 'd' => 3)); @@ -1533,7 +1602,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetIntersectionStore() { + function testZsetIntersectionStore() + { $zsetA = RC::zsetAddAndReturn($this->redis, 'zseta', array('a' => 1, 'b' => 2, 'c' => 3)); $zsetB = RC::zsetAddAndReturn($this->redis, 'zsetb', array('b' => 1, 'c' => 2, 'd' => 3)); @@ -1595,7 +1665,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetCount() { + function testZsetCount() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals(0, $this->redis->zcount('zset', 50, 100)); @@ -1612,7 +1683,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetCardinality() { + function testZsetCardinality() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals(count($zset), $this->redis->zcard('zset')); @@ -1634,7 +1706,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetScore() { + function testZsetScore() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals(-10, $this->redis->zscore('zset', 'a')); @@ -1650,7 +1723,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetRemoveRangeByScore() { + function testZsetRemoveRangeByScore() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals(2, $this->redis->zremrangebyscore('zset', -10, 0)); @@ -1678,7 +1752,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetRank() { + function testZsetRank() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals(0, $this->redis->zrank('zset', 'a')); @@ -1696,7 +1771,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetReverseRank() { + function testZsetReverseRank() + { $zset = RC::zsetAddAndReturn($this->redis, 'zset', RC::getZSetArray()); $this->assertEquals(5, $this->redis->zrevrank('zset', 'a')); @@ -1714,7 +1790,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testZsetRemoveRangeByRank() { + function testZsetRemoveRangeByRank() + { RC::zsetAddAndReturn($this->redis, 'zseta', RC::getZSetArray()); $this->assertEquals(3, $this->redis->zremrangebyrank('zseta', 0, 2)); @@ -1757,10 +1834,10 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - /* commands operating on hashes */ - function testHashSet() { + function testHashSet() + { $this->assertTrue($this->redis->hset('metavars', 'foo', 'bar')); $this->assertTrue($this->redis->hset('metavars', 'hoge', 'piyo')); $this->assertEquals('bar', $this->redis->hget('metavars', 'foo')); @@ -1772,7 +1849,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashGet() { + function testHashGet() + { $this->assertTrue($this->redis->hset('metavars', 'foo', 'bar')); $this->assertEquals('bar', $this->redis->hget('metavars', 'foo')); @@ -1786,14 +1864,16 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashExists() { + function testHashExists() + { $this->assertTrue($this->redis->hset('metavars', 'foo', 'bar')); $this->assertTrue($this->redis->hexists('metavars', 'foo')); $this->assertFalse($this->redis->hexists('metavars', 'hoge')); $this->assertFalse($this->redis->hexists('hashDoesNotExist', 'field')); } - function testHashDelete() { + function testHashDelete() + { $this->assertTrue($this->redis->hset('metavars', 'foo', 'bar')); $this->assertTrue($this->redis->hexists('metavars', 'foo')); $this->assertTrue($this->redis->hdel('metavars', 'foo')); @@ -1808,7 +1888,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashLength() { + function testHashLength() + { $this->assertTrue($this->redis->hset('metavars', 'foo', 'bar')); $this->assertTrue($this->redis->hset('metavars', 'hoge', 'piyo')); $this->assertTrue($this->redis->hset('metavars', 'foofoo', 'barbar')); @@ -1823,7 +1904,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashSetPreserve() { + function testHashSetPreserve() + { $this->assertTrue($this->redis->hsetnx('metavars', 'foo', 'bar')); $this->assertFalse($this->redis->hsetnx('metavars', 'foo', 'barbar')); $this->assertEquals('bar', $this->redis->hget('metavars', 'foo')); @@ -1834,7 +1916,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashSetAndGetMultiple() { + function testHashSetAndGetMultiple() + { $hashKVs = array('foo' => 'bar', 'hoge' => 'piyo'); // key=>value pairs via array instance @@ -1848,7 +1931,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertEquals(array('bar', 'piyo'), $this->redis->hmget('metavars', 'foo', 'hoge')); } - function testHashIncrementBy() { + function testHashIncrementBy() + { // test subsequent increment commands $this->assertEquals(10, $this->redis->hincrby('hash', 'counter', 10)); $this->assertEquals(20, $this->redis->hincrby('hash', 'counter', 10)); @@ -1865,7 +1949,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashKeys() { + function testHashKeys() + { $hashKVs = array('foo' => 'bar', 'hoge' => 'piyo'); $this->assertTrue($this->redis->hmset('metavars', $hashKVs)); @@ -1878,7 +1963,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashValues() { + function testHashValues() + { $hashKVs = array('foo' => 'bar', 'hoge' => 'piyo'); $this->assertTrue($this->redis->hmset('metavars', $hashKVs)); @@ -1891,7 +1977,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testHashGetAll() { + function testHashGetAll() + { $hashKVs = array('foo' => 'bar', 'hoge' => 'piyo'); $this->assertTrue($this->redis->hmset('metavars', $hashKVs)); @@ -1904,10 +1991,10 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - /* multiple databases handling commands */ - function testSelectDatabase() { + function testSelectDatabase() + { $this->assertTrue($this->redis->select(0)); $this->assertTrue($this->redis->select(RC::DEFAULT_DATABASE)); @@ -1920,7 +2007,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testMove() { + function testMove() + { // TODO: This test sucks big time. Period. $otherDb = 5; $this->redis->set('foo', 'bar'); @@ -1940,14 +2028,15 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - function testFlushdb() { + function testFlushdb() + { $this->assertTrue($this->redis->flushdb()); } - /* sorting */ - function testSort() { + function testSort() + { $unorderedList = RC::pushTailAndReturn($this->redis, 'unordered', array(2, 100, 3, 1, 30, 10)); // without parameters @@ -2032,10 +2121,10 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } - /* remote server control commands */ - function testInfo() { + function testInfo() + { $serverInfo = $this->redis->info(); $this->assertInternalType('array', $serverInfo); @@ -2044,7 +2133,8 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertGreaterThan(0, $serverInfo['total_connections_received']); } - function testSlaveOf() { + function testSlaveOf() + { $masterHost = 'www.google.com'; $masterPort = 80; @@ -2057,23 +2147,25 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { $this->assertTrue($this->redis->slaveof('NO ONE')); } - /* persistence control commands */ - function testSave() { + function testSave() + { $this->assertTrue($this->redis->save()); } - function testBackgroundSave() { + function testBackgroundSave() + { $this->assertTrue($this->redis->bgsave()); } - function testBackgroundRewriteAppendOnlyFile() { + function testBackgroundRewriteAppendOnlyFile() + { $this->assertTrue($this->redis->bgrewriteaof()); } - function testLastSave() { + function testLastSave() + { $this->assertGreaterThan(0, $this->redis->lastsave()); } } -?>