12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482 |
- <?php
- namespace Predis;
- class PredisException extends \Exception { }
- class ClientException extends PredisException { } // Client-side errors
- class AbortedMultiExec extends PredisException { } // Aborted multi/exec
- class ServerException extends PredisException { // Server-side errors
- public function toResponseError() {
- return new ResponseError($this->getMessage());
- }
- }
- class CommunicationException extends PredisException { // Communication errors
- private $_connection;
- public function __construct(Connection $connection, $message = null, $code = null) {
- $this->_connection = $connection;
- parent::__construct($message, $code);
- }
- public function getConnection() { return $this->_connection; }
- public function shouldResetConnection() { return true; }
- }
- class MalformedServerResponse extends CommunicationException { } // Unexpected responses
- /* ------------------------------------------------------------------------- */
- class Client {
- const VERSION = '0.6.6';
- private $_options, $_connection, $_serverProfile, $_responseReader;
- public function __construct($parameters = null, $clientOptions = null) {
- $this->setupClient($clientOptions ?: new ClientOptions());
- $this->setupConnection($parameters);
- }
- public static function create(/* arguments */) {
- $argv = func_get_args();
- $argc = func_num_args();
- $options = null;
- $lastArg = $argv[$argc-1];
- if ($argc > 0 && !is_string($lastArg) && ($lastArg instanceof ClientOptions ||
- is_subclass_of($lastArg, '\Predis\RedisServerProfile'))) {
- $options = array_pop($argv);
- $argc--;
- }
- if ($argc === 0) {
- throw new ClientException('Missing connection parameters');
- }
- return new Client($argc === 1 ? $argv[0] : $argv, $options);
- }
- private static function filterClientOptions($options) {
- if ($options instanceof ClientOptions) {
- return $options;
- }
- if (is_array($options)) {
- return new ClientOptions($options);
- }
- if ($options instanceof RedisServerProfile) {
- return new ClientOptions(array(
- 'profile' => $options
- ));
- }
- if (is_string($options)) {
- return new ClientOptions(array(
- 'profile' => RedisServerProfile::get($options)
- ));
- }
- throw new \InvalidArgumentException("Invalid type for client options");
- }
- private function setupClient($options) {
- $options = self::filterClientOptions($options);
- $this->setProfile($options->profile);
- $reader = $options->reader;
- $reader->setOption('iterable_multibulk', $options->iterable_multibulk);
- $reader->setOption('throw_on_error', $options->throw_on_error);
- $this->_options = $options;
- $this->_responseReader = $reader;
- }
- private function setupConnection($parameters) {
- if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
- throw new ClientException('Invalid parameters type (array or string expected)');
- }
- if (is_array($parameters) && isset($parameters[0])) {
- $cluster = new ConnectionCluster($this->_options->key_distribution);
- foreach ($parameters as $shardParams) {
- $cluster->add($this->createConnection($shardParams));
- }
- $this->setConnection($cluster);
- }
- else {
- $this->setConnection($this->createConnection($parameters));
- }
- }
- private function createConnection($parameters) {
- if (!$parameters instanceof ConnectionParameters) {
- $parameters = new ConnectionParameters($parameters);
- }
- $connection = new Connection($parameters, $this->_responseReader);
- if ($parameters->password !== null) {
- $connection->pushInitCommand($this->createCommand(
- 'auth', array($parameters->password)
- ));
- }
- if ($parameters->database !== null) {
- $connection->pushInitCommand($this->createCommand(
- 'select', array($parameters->database)
- ));
- }
- return $connection;
- }
- private function setConnection(IConnection $connection) {
- $this->_connection = $connection;
- }
- public function setProfile($serverProfile) {
- if ($serverProfile instanceof RedisServerProfile) {
- $this->_serverProfile = $serverProfile;
- }
- else if (is_string($serverProfile)) {
- $this->_serverProfile = RedisServerProfile::get($serverProfile);
- }
- else {
- throw new \InvalidArgumentException(
- "Invalid type for server profile, \Predis\RedisServerProfile or string expected"
- );
- }
- }
- public function getProfile() {
- return $this->_serverProfile;
- }
- public function getResponseReader() {
- return $this->_responseReader;
- }
- public function getClientFor($connectionAlias) {
- if (!Shared\Utils::isCluster($this->_connection)) {
- throw new ClientException(
- 'This method is supported only when the client is connected to a cluster of connections'
- );
- }
- $connection = $this->_connection->getConnectionById($connectionAlias);
- if ($connection === null) {
- throw new \InvalidArgumentException(
- "Invalid connection alias: '$connectionAlias'"
- );
- }
- $newClient = new Client();
- $newClient->setupClient($this->_options);
- $newClient->setConnection($connection);
- return $newClient;
- }
- public function connect() {
- $this->_connection->connect();
- }
- public function disconnect() {
- $this->_connection->disconnect();
- }
- public function isConnected() {
- return $this->_connection->isConnected();
- }
- public function getConnection($id = null) {
- if (!isset($id)) {
- return $this->_connection;
- }
- else {
- return Shared\Utils::isCluster($this->_connection)
- ? $this->_connection->getConnectionById($id)
- : $this->_connection;
- }
- }
- public function __call($method, $arguments) {
- $command = $this->_serverProfile->createCommand($method, $arguments);
- return $this->_connection->executeCommand($command);
- }
- public function createCommand($method, $arguments = array()) {
- return $this->_serverProfile->createCommand($method, $arguments);
- }
- public function executeCommand(Command $command) {
- return $this->_connection->executeCommand($command);
- }
- public function executeCommandOnShards(Command $command) {
- $replies = array();
- if (Shared\Utils::isCluster($this->_connection)) {
- foreach($this->_connection as $connection) {
- $replies[] = $connection->executeCommand($command);
- }
- }
- else {
- $replies[] = $this->_connection->executeCommand($command);
- }
- return $replies;
- }
- public function rawCommand($rawCommandData, $closesConnection = false) {
- if (Shared\Utils::isCluster($this->_connection)) {
- throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
- }
- return $this->_connection->rawCommand($rawCommandData, $closesConnection);
- }
- private function sharedInitializer($argv, $initializer) {
- $argc = count($argv);
- if ($argc === 0) {
- return $this->$initializer();
- }
- else if ($argc === 1) {
- list($arg0) = $argv;
- return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
- }
- else if ($argc === 2) {
- list($arg0, $arg1) = $argv;
- return $this->$initializer($arg0, $arg1);
- }
- return $this->$initializer($this, $arguments);
- }
- public function pipeline(/* arguments */) {
- return $this->sharedInitializer(func_get_args(), 'initPipeline');
- }
- public function pipelineSafe($pipelineBlock = null) {
- return $this->initPipeline(array('safe' => true), $pipelineBlock);
- }
- private function initPipeline(Array $options = null, $pipelineBlock = null) {
- $pipeline = null;
- if (isset($options)) {
- if (isset($options['safe']) && $options['safe'] == true) {
- $connection = $this->getConnection();
- $pipeline = new CommandPipeline($this, $connection instanceof Connection
- ? new Pipeline\SafeExecutor($connection)
- : new Pipeline\SafeClusterExecutor($connection)
- );
- }
- else {
- $pipeline = new CommandPipeline($this);
- }
- }
- else {
- $pipeline = new CommandPipeline($this);
- }
- return $this->pipelineExecute($pipeline, $pipelineBlock);
- }
- private function pipelineExecute(CommandPipeline $pipeline, $block) {
- return $block !== null ? $pipeline->execute($block) : $pipeline;
- }
- public function multiExec(/* arguments */) {
- return $this->sharedInitializer(func_get_args(), 'initMultiExec');
- }
- private function initMultiExec(Array $options = null, $transBlock = null) {
- $multi = isset($options) ? new MultiExecBlock($this, $options) : new MultiExecBlock($this);
- return $transBlock !== null ? $multi->execute($transBlock) : $multi;
- }
- public function pubSubContext(Array $options = null) {
- return new PubSubContext($this, $options);
- }
- }
- /* ------------------------------------------------------------------------- */
- interface IClientOptionsHandler {
- public function validate($option, $value);
- public function getDefault();
- }
- class ClientOptionsProfile implements IClientOptionsHandler {
- public function validate($option, $value) {
- if ($value instanceof \Predis\RedisServerProfile) {
- return $value;
- }
- if (is_string($value)) {
- return \Predis\RedisServerProfile::get($value);
- }
- throw new \InvalidArgumentException("Invalid value for option $option");
- }
- public function getDefault() {
- return \Predis\RedisServerProfile::getDefault();
- }
- }
- class ClientOptionsKeyDistribution implements IClientOptionsHandler {
- public function validate($option, $value) {
- if ($value instanceof \Predis\Distribution\IDistributionStrategy) {
- return $value;
- }
- if (is_string($value)) {
- $valueReflection = new \ReflectionClass($value);
- if ($valueReflection->isSubclassOf('\Predis\Distribution\IDistributionStrategy')) {
- return new $value;
- }
- }
- throw new \InvalidArgumentException("Invalid value for option $option");
- }
- public function getDefault() {
- return new \Predis\Distribution\HashRing();
- }
- }
- class ClientOptionsIterableMultiBulk implements IClientOptionsHandler {
- public function validate($option, $value) {
- return (bool) $value;
- }
- public function getDefault() {
- return false;
- }
- }
- class ClientOptionsThrowOnError implements IClientOptionsHandler {
- public function validate($option, $value) {
- return (bool) $value;
- }
- public function getDefault() {
- return true;
- }
- }
- class ClientOptionsReader implements IClientOptionsHandler {
- public function validate($option, $value) {
- if ($value instanceof \Predis\IResponseReader) {
- return $value;
- }
- if (is_string($value)) {
- if ($value === 'composable') {
- return new \Predis\ResponseReader();
- }
- $valueReflection = new \ReflectionClass($value);
- if ($valueReflection->isSubclassOf('\Predis\IResponseReader')) {
- return new $value;
- }
- }
- throw new \InvalidArgumentException("Invalid value for option $option");
- }
- public function getDefault() {
- return new \Predis\FastResponseReader();
- }
- }
- class ClientOptions {
- private static $_optionsHandlers;
- private $_options;
- public function __construct($options = null) {
- self::initializeOptionsHandlers();
- $this->initializeOptions($options ?: array());
- }
- private static function initializeOptionsHandlers() {
- if (!isset(self::$_optionsHandlers)) {
- self::$_optionsHandlers = self::getOptionsHandlers();
- }
- }
- private static function getOptionsHandlers() {
- return array(
- 'profile' => new \Predis\ClientOptionsProfile(),
- 'key_distribution' => new \Predis\ClientOptionsKeyDistribution(),
- 'iterable_multibulk' => new \Predis\ClientOptionsIterableMultiBulk(),
- 'throw_on_error' => new \Predis\ClientOptionsThrowOnError(),
- 'reader' => new \Predis\ClientOptionsReader(),
- );
- }
- private function initializeOptions($options) {
- foreach ($options as $option => $value) {
- if (isset(self::$_optionsHandlers[$option])) {
- $handler = self::$_optionsHandlers[$option];
- $this->_options[$option] = $handler->validate($option, $value);
- }
- }
- }
- public function __get($option) {
- if (!isset($this->_options[$option])) {
- $defaultValue = self::$_optionsHandlers[$option]->getDefault();
- $this->_options[$option] = $defaultValue;
- }
- return $this->_options[$option];
- }
- public function __isset($option) {
- return isset(self::$_optionsHandlers[$option]);
- }
- }
- /* ------------------------------------------------------------------------- */
- class Protocol {
- const NEWLINE = "\r\n";
- const OK = 'OK';
- const ERROR = 'ERR';
- const QUEUED = 'QUEUED';
- const NULL = 'nil';
- const PREFIX_STATUS = '+';
- const PREFIX_ERROR = '-';
- const PREFIX_INTEGER = ':';
- const PREFIX_BULK = '$';
- const PREFIX_MULTI_BULK = '*';
- }
- abstract class Command {
- private $_hash;
- private $_arguments = array();
- public abstract function getCommandId();
- public abstract function serializeRequest($command, $arguments);
- public function canBeHashed() {
- return true;
- }
- public function getHash(Distribution\IDistributionStrategy $distributor) {
- if (isset($this->_hash)) {
- return $this->_hash;
- }
- if (isset($this->_arguments[0])) {
- // TODO: should we throw an exception if the command does
- // not support sharding?
- $key = $this->_arguments[0];
- $start = strpos($key, '{');
- if ($start !== false) {
- $end = strpos($key, '}', $start);
- if ($end !== false) {
- $key = substr($key, ++$start, $end - $start);
- }
- }
- $this->_hash = $distributor->generateKey($key);
- return $this->_hash;
- }
- return null;
- }
- public function closesConnection() {
- return false;
- }
- protected function filterArguments(Array $arguments) {
- return $arguments;
- }
- public function setArguments(/* arguments */) {
- $this->_arguments = $this->filterArguments(func_get_args());
- unset($this->_hash);
- }
- public function setArgumentsArray(Array $arguments) {
- $this->_arguments = $this->filterArguments($arguments);
- unset($this->_hash);
- }
- public function getArguments() {
- return $this->_arguments;
- }
- public function getArgument($index = 0) {
- if (isset($this->_arguments[$index]) === true) {
- return $this->_arguments[$index];
- }
- }
- public function parseResponse($data) {
- return $data;
- }
- public final function __invoke() {
- return $this->serializeRequest($this->getCommandId(), $this->getArguments());
- }
- private static function reduceArguments($str, $arg) {
- if (strlen($arg) > 32) {
- $arg = substr($arg, 0, 32) . '[...]';
- }
- $str .= " $arg";
- return $str;
- }
- public function __toString() {
- return array_reduce($this->getArguments(), 'self::reduceArguments', $this->getCommandId());
- }
- }
- abstract class InlineCommand extends Command {
- public function serializeRequest($command, $arguments) {
- if (isset($arguments[0]) && is_array($arguments[0])) {
- $arguments[0] = implode($arguments[0], ' ');
- }
- return $command . (count($arguments) > 0
- ? ' ' . implode($arguments, ' ') . "\r\n" : "\r\n"
- );
- }
- }
- abstract class BulkCommand extends Command {
- public function serializeRequest($command, $arguments) {
- $data = array_pop($arguments);
- if (is_array($data)) {
- $data = implode($data, ' ');
- }
- return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
- "\r\n" . $data . "\r\n";
- }
- }
- abstract class MultiBulkCommand extends Command {
- public function serializeRequest($command, $arguments) {
- $cmd_args = null;
- $argsc = count($arguments);
- if ($argsc === 1 && is_array($arguments[0])) {
- $cmd_args = $arguments[0];
- $argsc = count($cmd_args);
- }
- else {
- $cmd_args = $arguments;
- }
- $cmdlen = strlen($command);
- $reqlen = $argsc + 1;
- $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$command}\r\n";
- for ($i = 0; $i < $reqlen - 1; $i++) {
- $argument = $cmd_args[$i];
- $arglen = strlen($argument);
- $buffer .= "\${$arglen}\r\n{$argument}\r\n";
- }
- return $buffer;
- }
- }
- /* ------------------------------------------------------------------------- */
- interface IResponseHandler {
- function handle(Connection $connection, $payload);
- }
- class ResponseStatusHandler implements IResponseHandler {
- public function handle(Connection $connection, $status) {
- if ($status === 'OK') {
- return true;
- }
- if ($status === 'QUEUED') {
- return new ResponseQueued();
- }
- return $status;
- }
- }
- class ResponseErrorHandler implements IResponseHandler {
- public function handle(Connection $connection, $errorMessage) {
- throw new ServerException(substr($errorMessage, 4));
- }
- }
- class ResponseErrorSilentHandler implements IResponseHandler {
- public function handle(Connection $connection, $errorMessage) {
- return new ResponseError(substr($errorMessage, 4));
- }
- }
- class ResponseBulkHandler implements IResponseHandler {
- public function handle(Connection $connection, $lengthString) {
- $length = (int) $lengthString;
- if ($length != $lengthString) {
- Shared\Utils::onCommunicationException(new MalformedServerResponse(
- $connection, "Cannot parse '$length' as data length"
- ));
- }
- if ($length >= 0) {
- return substr($connection->readBytes($length + 2), 0, -2);
- }
- if ($length == -1) {
- return null;
- }
- }
- }
- class ResponseMultiBulkHandler implements IResponseHandler {
- public function handle(Connection $connection, $lengthString) {
- $listLength = (int) $lengthString;
- if ($listLength != $lengthString) {
- Shared\Utils::onCommunicationException(new MalformedServerResponse(
- $connection, "Cannot parse '$lengthString' as data length"
- ));
- }
- if ($listLength === -1) {
- return null;
- }
- $list = array();
- if ($listLength > 0) {
- $handlers = array();
- $reader = $connection->getResponseReader();
- for ($i = 0; $i < $listLength; $i++) {
- $header = $connection->readLine();
- $prefix = $header[0];
- if (isset($handlers[$prefix])) {
- $handler = $handlers[$prefix];
- }
- else {
- $handler = $reader->getHandler($prefix);
- $handlers[$prefix] = $handler;
- }
- $list[$i] = $handler->handle($connection, substr($header, 1));
- }
- }
- return $list;
- }
- }
- class ResponseMultiBulkStreamHandler implements IResponseHandler {
- public function handle(Connection $connection, $lengthString) {
- $listLength = (int) $lengthString;
- if ($listLength != $lengthString) {
- Shared\Utils::onCommunicationException(new MalformedServerResponse(
- $connection, "Cannot parse '$lengthString' as data length"
- ));
- }
- return new Shared\MultiBulkResponseIterator($connection, $lengthString);
- }
- }
- class ResponseIntegerHandler implements IResponseHandler {
- public function handle(Connection $connection, $number) {
- if (is_numeric($number)) {
- return (int) $number;
- }
- if ($number !== 'nil') {
- Shared\Utils::onCommunicationException(new MalformedServerResponse(
- $connection, "Cannot parse '$number' as numeric response"
- ));
- }
- return null;
- }
- }
- interface IResponseReader {
- public function read(Connection $connection);
- public function setOption($option, $value);
- public function getOption($option);
- }
- class FastResponseReader implements IResponseReader {
- private $_iterableMultibulk, $_throwErrors;
- public function __construct() {
- $this->_iterableMultibulk = false;
- $this->_throwErrors = true;
- }
- public function read(Connection $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;
- }
- case '$': // bulk
- $size = (int) $payload;
- if ($size === -1) {
- return null;
- }
- return substr($connection->readBytes($size + 2), 0, -2);
- case '*': // multi bulk
- $count = (int) $payload;
- if ($count === -1) {
- return null;
- }
- if ($this->_iterableMultibulk) {
- return new \Predis\Shared\MultiBulkResponseIterator($connection, $count);
- }
- $multibulk = array();
- for ($i = 0; $i < $count; $i++) {
- $multibulk[$i] = $this->read($connection);
- }
- return $multibulk;
- case ':': // integer
- return (int) $payload;
- case '-': // error
- $errorMessage = substr($payload, 4);
- if ($this->_throwErrors) {
- throw new ServerException($errorMessage);
- }
- return new ResponseError($errorMessage);
- default:
- throw new CommunicationException(
- $connection, "Unknown prefix: '$prefix'"
- );
- }
- }
- public function setOption($option, $value) {
- switch ($option) {
- case 'iterable_multibulk':
- $this->_iterableMultibulk = (bool) $value;
- break;
- case 'throw_on_error':
- $this->_throwErrors = (bool) $value;
- break;
- }
- }
- public function getOption($option) {
- switch ($option) {
- case 'iterable_multibulk':
- return $this->_iterableMultibulk;
- case 'throw_on_error':
- return $this->_throwErrors;
- }
- }
- }
- class ResponseReader implements IResponseReader {
- private $_prefixHandlers;
- public function __construct() {
- $this->initializePrefixHandlers();
- }
- private function initializePrefixHandlers() {
- $this->_prefixHandlers = array(
- Protocol::PREFIX_STATUS => new ResponseStatusHandler(),
- Protocol::PREFIX_ERROR => new ResponseErrorHandler(),
- Protocol::PREFIX_INTEGER => new ResponseIntegerHandler(),
- Protocol::PREFIX_BULK => new ResponseBulkHandler(),
- Protocol::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
- );
- }
- public function setHandler($prefix, IResponseHandler $handler) {
- $this->_prefixHandlers[$prefix] = $handler;
- }
- public function getHandler($prefix) {
- if (isset($this->_prefixHandlers[$prefix])) {
- return $this->_prefixHandlers[$prefix];
- }
- }
- public function read(Connection $connection) {
- $header = $connection->readLine();
- if ($header === '') {
- $this->throwMalformedResponse($connection, 'Unexpected empty header');
- }
- $prefix = $header[0];
- if (!isset($this->_prefixHandlers[$prefix])) {
- $this->throwMalformedResponse($connection, "Unknown prefix '$prefix'");
- }
- $handler = $this->_prefixHandlers[$prefix];
- return $handler->handle($connection, substr($header, 1));
- }
- private function throwMalformedResponse(Connection $connection, $message) {
- Shared\Utils::onCommunicationException(new MalformedServerResponse(
- $connection, $message
- ));
- }
- public function setOption($option, $value) {
- switch ($option) {
- case 'iterable_multibulk':
- $handler = $value ? 'Predis\ResponseMultiBulkStreamHandler' : 'Predis\ResponseMultiBulkHandler';
- $this->_prefixHandlers[Protocol::PREFIX_MULTI_BULK] = new $handler();
- break;
- case 'throw_on_error':
- $handler = $value ? 'Predis\ResponseErrorHandler' : 'Predis\ResponseErrorSilentHandler';
- $this->_prefixHandlers[Protocol::PREFIX_ERROR] = new $handler();
- break;
- }
- }
- public function getOption($option) {
- switch ($option) {
- case 'iterable_multibulk':
- return $this->_prefixHandlers[Protocol::PREFIX_MULTI_BULK] instanceof ResponseMultiBulkStreamHandler;
- case 'throw_on_error':
- return $this->_prefixHandlers[Protocol::PREFIX_ERROR] instanceof ResponseErrorHandler;
- }
- }
- }
- class ResponseError {
- public $skipParse = true;
- private $_message;
- public function __construct($message) {
- $this->_message = $message;
- }
- public function __get($property) {
- if ($property === 'error') {
- return true;
- }
- if ($property === 'message') {
- return $this->_message;
- }
- }
- public function __isset($property) {
- return $property === 'error';
- }
- public function __toString() {
- return $this->_message;
- }
- }
- class ResponseQueued {
- public $skipParse = true;
- public function __toString() {
- return Protocol::QUEUED;
- }
- public function __get($property) {
- if ($property === 'queued') {
- return true;
- }
- }
- public function __isset($property) {
- return $property === 'queued';
- }
- }
- /* ------------------------------------------------------------------------- */
- class CommandPipeline {
- private $_redisClient, $_pipelineBuffer, $_returnValues, $_running, $_executor;
- public function __construct(Client $redisClient, Pipeline\IPipelineExecutor $executor = null) {
- $this->_redisClient = $redisClient;
- $this->_executor = $executor ?: new Pipeline\StandardExecutor();
- $this->_pipelineBuffer = array();
- $this->_returnValues = array();
- }
- public function __call($method, $arguments) {
- $command = $this->_redisClient->createCommand($method, $arguments);
- $this->recordCommand($command);
- return $this;
- }
- private function recordCommand(Command $command) {
- $this->_pipelineBuffer[] = $command;
- }
- private function getRecordedCommands() {
- return $this->_pipelineBuffer;
- }
- public function flushPipeline() {
- if (count($this->_pipelineBuffer) > 0) {
- $connection = $this->_redisClient->getConnection();
- $this->_returnValues = array_merge(
- $this->_returnValues,
- $this->_executor->execute($connection, $this->_pipelineBuffer)
- );
- $this->_pipelineBuffer = array();
- }
- return $this;
- }
- 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) {
- if ($block && !is_callable($block)) {
- throw new \InvalidArgumentException('Argument passed must be a callable object');
- }
- // TODO: do not reuse previously executed pipelines
- $this->setRunning(true);
- $pipelineBlockException = null;
- try {
- if ($block !== null) {
- $block($this);
- }
- $this->flushPipeline();
- }
- catch (\Exception $exception) {
- $pipelineBlockException = $exception;
- }
- $this->setRunning(false);
- if ($pipelineBlockException !== null) {
- throw $pipelineBlockException;
- }
- return $this->_returnValues;
- }
- }
- class MultiExecBlock {
- private $_initialized, $_discarded, $_insideBlock, $_checkAndSet, $_watchedKeys;
- private $_redisClient, $_options, $_commands;
- private $_supportsWatch;
- public function __construct(Client $redisClient, Array $options = null) {
- $this->checkCapabilities($redisClient);
- $this->_options = $options ?: array();
- $this->_redisClient = $redisClient;
- $this->reset();
- }
- private function checkCapabilities(Client $redisClient) {
- if (Shared\Utils::isCluster($redisClient->getConnection())) {
- throw new \Predis\ClientException(
- 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
- );
- }
- $profile = $redisClient->getProfile();
- if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
- throw new \Predis\ClientException(
- 'The current profile does not support MULTI, EXEC and DISCARD commands'
- );
- }
- $this->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
- }
- private function isWatchSupported() {
- if ($this->_supportsWatch === false) {
- throw new \Predis\ClientException(
- 'The current profile does not support WATCH and UNWATCH commands'
- );
- }
- }
- private function reset() {
- $this->_initialized = false;
- $this->_discarded = false;
- $this->_checkAndSet = false;
- $this->_insideBlock = false;
- $this->_watchedKeys = false;
- $this->_commands = array();
- }
- private function initialize() {
- if ($this->_initialized === true) {
- return;
- }
- $options = &$this->_options;
- $this->_checkAndSet = isset($options['cas']) && $options['cas'];
- if (isset($options['watch'])) {
- $this->watch($options['watch']);
- }
- if (!$this->_checkAndSet || ($this->_discarded && $this->_checkAndSet)) {
- $this->_redisClient->multi();
- if ($this->_discarded) {
- $this->_checkAndSet = false;
- }
- }
- $this->_initialized = true;
- $this->_discarded = false;
- }
- public function __call($method, $arguments) {
- $this->initialize();
- $client = $this->_redisClient;
- if ($this->_checkAndSet) {
- return call_user_func_array(array($client, $method), $arguments);
- }
- $command = $client->createCommand($method, $arguments);
- $response = $client->executeCommand($command);
- if (!$response instanceof \Predis\ResponseQueued) {
- $this->malformedServerResponse(
- 'The server did not respond with a QUEUED status reply'
- );
- }
- $this->_commands[] = $command;
- return $this;
- }
- public function watch($keys) {
- $this->isWatchSupported();
- if ($this->_initialized && !$this->_checkAndSet) {
- throw new ClientException('WATCH inside MULTI is not allowed');
- }
- $this->_watchedKeys = true;
- return $this->_redisClient->watch($keys);
- }
- public function multi() {
- if ($this->_initialized && $this->_checkAndSet) {
- $this->_checkAndSet = false;
- $this->_redisClient->multi();
- return $this;
- }
- $this->initialize();
- return $this;
- }
- public function unwatch() {
- $this->isWatchSupported();
- $this->_watchedKeys = false;
- $this->_redisClient->unwatch();
- return $this;
- }
- public function discard() {
- if ($this->_initialized === true) {
- $command = $this->_checkAndSet ? 'unwatch' : 'discard';
- $this->_redisClient->$command();
- $this->reset();
- $this->_discarded = true;
- }
- return $this;
- }
- public function exec() {
- return $this->execute();
- }
- private function checkBeforeExecution($block) {
- if ($this->_insideBlock === true) {
- throw new \Predis\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(
- 'Cannot execute a transaction block after using fluent interface'
- );
- }
- }
- if (isset($this->_options['retry']) && !isset($block)) {
- $this->discard();
- throw new \InvalidArgumentException(
- 'Automatic retries can be used only when a transaction block is provided'
- );
- }
- }
- public function execute($block = null) {
- $this->checkBeforeExecution($block);
- $reply = null;
- $returnValues = array();
- $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
- do {
- $blockException = null;
- if ($block !== null) {
- $this->_insideBlock = true;
- try {
- $block($this);
- }
- catch (CommunicationException $exception) {
- $blockException = $exception;
- }
- catch (ServerException $exception) {
- $blockException = $exception;
- }
- catch (\Exception $exception) {
- $blockException = $exception;
- $this->discard();
- }
- $this->_insideBlock = false;
- if ($blockException !== null) {
- throw $blockException;
- }
- }
- if (count($this->_commands) === 0) {
- if ($this->_watchedKeys) {
- $this->discard();
- return;
- }
- return;
- }
- $reply = $this->_redisClient->exec();
- if ($reply === null) {
- if ($attemptsLeft === 0) {
- throw new AbortedMultiExec(
- 'The current transaction has been aborted by the server'
- );
- }
- $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->malformedServerResponse(
- 'Unexpected number of responses for a MultiExecBlock'
- );
- }
- for ($i = 0; $i < $sizeofReplies; $i++) {
- $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
- ? iterator_to_array($execReply[$i])
- : $execReply[$i]
- );
- unset($commands[$i]);
- }
- return $returnValues;
- }
- private function malformedServerResponse($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\Connection.
- Shared\Utils::onCommunicationException(new MalformedServerResponse(
- $this->_redisClient->getConnection(), $message
- ));
- }
- }
- class PubSubContext implements \Iterator {
- const SUBSCRIBE = 'subscribe';
- const UNSUBSCRIBE = 'unsubscribe';
- const PSUBSCRIBE = 'psubscribe';
- const PUNSUBSCRIBE = 'punsubscribe';
- const MESSAGE = 'message';
- const PMESSAGE = 'pmessage';
- const STATUS_VALID = 0x0001;
- const STATUS_SUBSCRIBED = 0x0010;
- const STATUS_PSUBSCRIBED = 0x0100;
- private $_redisClient, $_position, $_options;
- public function __construct(Client $redisClient, Array $options = null) {
- $this->checkCapabilities($redisClient);
- $this->_options = $options ?: array();
- $this->_redisClient = $redisClient;
- $this->_statusFlags = self::STATUS_VALID;
- $this->genericSubscribeInit('subscribe');
- $this->genericSubscribeInit('psubscribe');
- }
- public function __destruct() {
- $this->closeContext();
- }
- private function checkCapabilities(Client $redisClient) {
- if (Shared\Utils::isCluster($redisClient->getConnection())) {
- throw new \Predis\ClientException(
- 'Cannot initialize a PUB/SUB context over a cluster of connections'
- );
- }
- $profile = $redisClient->getProfile();
- $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
- if ($profile->supportsCommands($commands) === false) {
- throw new \Predis\ClientException(
- 'The current profile does not support PUB/SUB related commands'
- );
- }
- }
- private function genericSubscribeInit($subscribeAction) {
- if (isset($this->_options[$subscribeAction])) {
- $this->$subscribeAction($this->_options[$subscribeAction]);
- }
- }
- private function isFlagSet($value) {
- return ($this->_statusFlags & $value) === $value;
- }
- public function subscribe(/* arguments */) {
- $this->writeCommand(self::SUBSCRIBE, func_get_args());
- $this->_statusFlags |= self::STATUS_SUBSCRIBED;
- }
- public function unsubscribe(/* arguments */) {
- $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
- }
- public function psubscribe(/* arguments */) {
- $this->writeCommand(self::PSUBSCRIBE, func_get_args());
- $this->_statusFlags |= self::STATUS_PSUBSCRIBED;
- }
- public function punsubscribe(/* arguments */) {
- $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
- }
- public function closeContext() {
- if ($this->valid()) {
- if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
- $this->unsubscribe();
- }
- if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
- $this->punsubscribe();
- }
- }
- }
- private function writeCommand($method, $arguments) {
- if (count($arguments) === 1 && is_array($arguments[0])) {
- $arguments = $arguments[0];
- }
- $command = $this->_redisClient->createCommand($method, $arguments);
- $this->_redisClient->getConnection()->writeCommand($command);
- }
- public function rewind() {
- // NOOP
- }
- public function current() {
- return $this->getValue();
- }
- public function key() {
- return $this->_position;
- }
- public function next() {
- if ($this->isFlagSet(self::STATUS_VALID)) {
- $this->_position++;
- }
- return $this->_position;
- }
- public function valid() {
- $subscriptions = self::STATUS_SUBSCRIBED + self::STATUS_PSUBSCRIBED;
- return $this->isFlagSet(self::STATUS_VALID)
- && ($this->_statusFlags & $subscriptions) > 0;
- }
- private function invalidate() {
- $this->_statusFlags = 0x0000;
- }
- private function getValue() {
- $reader = $this->_redisClient->getResponseReader();
- $connection = $this->_redisClient->getConnection();
- $response = $reader->read($connection);
- switch ($response[0]) {
- case self::SUBSCRIBE:
- case self::UNSUBSCRIBE:
- case self::PSUBSCRIBE:
- case self::PUNSUBSCRIBE:
- 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],
- 'pattern' => $response[1],
- 'channel' => $response[2],
- 'payload' => $response[3],
- );
- default:
- throw new \Predis\ClientException(
- "Received an unknown message type {$response[0]} inside of a pubsub context"
- );
- }
- }
- }
- /* ------------------------------------------------------------------------- */
- class ConnectionParameters {
- const DEFAULT_SCHEME = 'redis';
- const DEFAULT_HOST = '127.0.0.1';
- const DEFAULT_PORT = 6379;
- const DEFAULT_TIMEOUT = 5;
- private static $_defaultParameters = array(
- 'scheme' => self::DEFAULT_SCHEME,
- 'host' => self::DEFAULT_HOST,
- 'port' => self::DEFAULT_PORT,
- 'database' => null,
- 'password' => null,
- 'connection_async' => false,
- 'connection_persistent' => false,
- 'connection_timeout' => self::DEFAULT_TIMEOUT,
- 'read_write_timeout' => null,
- 'alias' => null,
- 'weight' => null,
- 'path' => null,
- );
- private $_parameters;
- public function __construct($parameters = null) {
- $parameters = $parameters ?: array();
- $extractor = is_array($parameters) ? 'filter' : 'parseURI';
- $this->_parameters = $this->$extractor($parameters);
- }
- 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);
- $parsed[$k] = $v;
- }
- unset($parsed['query']);
- }
- return $this->filter($parsed);
- }
- private function filter($parameters) {
- return array_merge(self::$_defaultParameters, $parameters);
- }
- public function __get($parameter) {
- return $this->_parameters[$parameter];
- }
- public function __isset($parameter) {
- return isset($this->_parameters[$parameter]);
- }
- }
- interface IConnection {
- public function connect();
- public function disconnect();
- public function isConnected();
- public function writeCommand(Command $command);
- public function readResponse(Command $command);
- public function executeCommand(Command $command);
- }
- class Connection implements IConnection {
- private static $_allowedSchemes = array('redis', 'tcp', 'unix');
- private $_params, $_socket, $_initCmds, $_reader;
- public function __construct(ConnectionParameters $parameters, IResponseReader $reader = null) {
- if (!in_array($parameters->scheme, self::$_allowedSchemes)) {
- throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
- }
- $this->_params = $parameters;
- $this->_initCmds = array();
- $this->_reader = $reader ?: new FastResponseReader();
- }
- public function __destruct() {
- if (!$this->_params->connection_persistent) {
- $this->disconnect();
- }
- }
- public function isConnected() {
- return isset($this->_socket);
- }
- public function connect() {
- if ($this->isConnected()) {
- throw new ClientException('Connection already estabilished');
- }
- $initializer = "{$this->_params->scheme}StreamInitializer";
- $this->_socket = $this->$initializer($this->_params);
- if (count($this->_initCmds) > 0){
- $this->sendInitializationCommands();
- }
- }
- private function tcpStreamInitializer(ConnectionParameters $parameters) {
- return $this->redisStreamInitializer($parameters);
- }
- private function redisStreamInitializer(ConnectionParameters $parameters) {
- $uri = sprintf('tcp://%s:%d/', $parameters->host, $parameters->port);
- $connectFlags = STREAM_CLIENT_CONNECT;
- if ($parameters->connection_async) {
- $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
- }
- if ($parameters->connection_persistent) {
- $connectFlags |= STREAM_CLIENT_PERSISTENT;
- }
- $socket = @stream_socket_client(
- $uri, $errno, $errstr, $parameters->connection_timeout, $connectFlags
- );
- if (!$socket) {
- $this->onCommunicationException(trim($errstr), $errno);
- }
- if (isset($parameters->read_write_timeout)) {
- $rwtimeout = $parameters->read_write_timeout;
- $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
- $timeoutSeconds = floor($parameters->read_write_timeout);
- $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
- stream_set_timeout($socket, $rwtimeout, $timeoutUSeconds);
- }
- return $socket;
- }
- private function unixStreamInitializer(ConnectionParameters $parameters) {
- $uri = sprintf('unix:///%s', $parameters->path);
- $connectFlags = STREAM_CLIENT_CONNECT;
- if ($parameters->connection_persistent) {
- $connectFlags |= STREAM_CLIENT_PERSISTENT;
- }
- $socket = @stream_socket_client(
- $uri, $errno, $errstr, $parameters->connection_timeout, $connectFlags
- );
- if (!$socket) {
- $this->onCommunicationException(trim($errstr), $errno);
- }
- return $socket;
- }
- public function disconnect() {
- if ($this->isConnected()) {
- fclose($this->_socket);
- unset($this->_socket);
- }
- }
- public function pushInitCommand(Command $command){
- $this->_initCmds[] = $command;
- }
- private function sendInitializationCommands() {
- foreach ($this->_initCmds as $command) {
- $this->writeCommand($command);
- }
- foreach ($this->_initCmds as $command) {
- $this->readResponse($command);
- }
- }
- private function onCommunicationException($message, $code = null) {
- Shared\Utils::onCommunicationException(
- new CommunicationException($this, $message, $code)
- );
- }
- public function writeCommand(Command $command) {
- $this->writeBytes($command());
- }
- public function readResponse(Command $command) {
- $response = $this->_reader->read($this);
- return isset($response->skipParse) ? $response : $command->parseResponse($response);
- }
- public function executeCommand(Command $command) {
- $this->writeCommand($command);
- if ($command->closesConnection()) {
- return $this->disconnect();
- }
- return $this->readResponse($command);
- }
- public function rawCommand($rawCommandData, $closesConnection = false) {
- $this->writeBytes($rawCommandData);
- if ($closesConnection) {
- $this->disconnect();
- return;
- }
- return $this->_reader->read($this);
- }
- public function writeBytes($value) {
- $socket = $this->getSocket();
- while (($length = strlen($value)) > 0) {
- $written = fwrite($socket, $value);
- if ($length === $written) {
- return true;
- }
- if ($written === false || $written === 0) {
- $this->onCommunicationException('Error while writing bytes to the server');
- }
- $value = substr($value, $written);
- }
- return true;
- }
- public function readBytes($length) {
- if ($length <= 0) {
- throw new \InvalidArgumentException('Length parameter must be greater than 0');
- }
- $socket = $this->getSocket();
- $value = '';
- do {
- $chunk = fread($socket, $length);
- if ($chunk === false || $chunk === '') {
- $this->onCommunicationException('Error while reading bytes from the server');
- }
- $value .= $chunk;
- }
- while (($length -= strlen($chunk)) > 0);
- return $value;
- }
- public function readLine() {
- $socket = $this->getSocket();
- $value = '';
- do {
- $chunk = fgets($socket);
- if ($chunk === false || $chunk === '') {
- $this->onCommunicationException('Error while reading line from the server');
- }
- $value .= $chunk;
- }
- while (substr($value, -2) !== "\r\n");
- return substr($value, 0, -2);
- }
- public function getSocket() {
- if (isset($this->_socket)) {
- return $this->_socket;
- }
- $this->connect();
- return $this->_socket;
- }
- public function getResponseReader() {
- return $this->_reader;
- }
- public function getParameters() {
- return $this->_params;
- }
- public function __toString() {
- return sprintf('%s:%d', $this->_params->host, $this->_params->port);
- }
- }
- class ConnectionCluster implements IConnection, \IteratorAggregate {
- private $_pool, $_distributor;
- public function __construct(Distribution\IDistributionStrategy $distributor = null) {
- $this->_pool = array();
- $this->_distributor = $distributor ?: new Distribution\HashRing();
- }
- public function isConnected() {
- foreach ($this->_pool as $connection) {
- if ($connection->isConnected()) {
- return true;
- }
- }
- return false;
- }
- public function connect() {
- foreach ($this->_pool as $connection) {
- $connection->connect();
- }
- }
- public function disconnect() {
- foreach ($this->_pool as $connection) {
- $connection->disconnect();
- }
- }
- public function add(Connection $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(Command $command) {
- if ($command->canBeHashed() === false) {
- throw new ClientException(
- sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
- );
- }
- return $this->_distributor->get($command->getHash($this->_distributor));
- }
- public function getConnectionById($id = null) {
- $alias = $id ?: 0;
- return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
- }
- public function getIterator() {
- return new \ArrayIterator($this->_pool);
- }
- public function writeCommand(Command $command) {
- $this->getConnection($command)->writeCommand($command);
- }
- public function readResponse(Command $command) {
- return $this->getConnection($command)->readResponse($command);
- }
- public function executeCommand(Command $command) {
- $connection = $this->getConnection($command);
- $connection->writeCommand($command);
- return $connection->readResponse($command);
- }
- }
- /* ------------------------------------------------------------------------- */
- abstract class RedisServerProfile {
- private static $_serverProfiles;
- private $_registeredCommands;
- public function __construct() {
- $this->_registeredCommands = $this->getSupportedCommands();
- }
- public abstract function getVersion();
- protected abstract function getSupportedCommands();
- public static function getDefault() {
- return self::get('default');
- }
- public static function getDevelopment() {
- return self::get('dev');
- }
- private static function predisServerProfiles() {
- return array(
- '1.2' => '\Predis\RedisServer_v1_2',
- '2.0' => '\Predis\RedisServer_v2_0',
- '2.2' => '\Predis\RedisServer_v2_2',
- 'default' => '\Predis\RedisServer_v2_2',
- 'dev' => '\Predis\RedisServer_vNext',
- );
- }
- public static function registerProfile($profileClass, $aliases) {
- if (!isset(self::$_serverProfiles)) {
- self::$_serverProfiles = self::predisServerProfiles();
- }
- $profileReflection = new \ReflectionClass($profileClass);
- if (!$profileReflection->isSubclassOf('\Predis\RedisServerProfile')) {
- throw new ClientException("Cannot register '$profileClass' as it is not a valid profile class");
- }
- if (is_array($aliases)) {
- foreach ($aliases as $alias) {
- self::$_serverProfiles[$alias] = $profileClass;
- }
- }
- else {
- self::$_serverProfiles[$aliases] = $profileClass;
- }
- }
- public static function get($version) {
- if (!isset(self::$_serverProfiles)) {
- self::$_serverProfiles = self::predisServerProfiles();
- }
- if (!isset(self::$_serverProfiles[$version])) {
- throw new ClientException("Unknown server profile: $version");
- }
- $profile = self::$_serverProfiles[$version];
- return new $profile();
- }
- public function supportsCommands(Array $commands) {
- foreach ($commands as $command) {
- if ($this->supportsCommand($command) === false) {
- return false;
- }
- }
- return true;
- }
- public function supportsCommand($command) {
- return isset($this->_registeredCommands[$command]);
- }
- public function createCommand($method, $arguments = array()) {
- if (!isset($this->_registeredCommands[$method])) {
- throw new ClientException("'$method' is not a registered Redis command");
- }
- $commandClass = $this->_registeredCommands[$method];
- $command = new $commandClass();
- $command->setArgumentsArray($arguments);
- return $command;
- }
- public function registerCommands(Array $commands) {
- foreach ($commands as $command => $aliases) {
- $this->registerCommand($command, $aliases);
- }
- }
- public function registerCommand($command, $aliases) {
- $commandReflection = new \ReflectionClass($command);
- if (!$commandReflection->isSubclassOf('\Predis\Command')) {
- throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
- }
- if (is_array($aliases)) {
- foreach ($aliases as $alias) {
- $this->_registeredCommands[$alias] = $command;
- }
- }
- else {
- $this->_registeredCommands[$aliases] = $command;
- }
- }
- public function __toString() {
- return $this->getVersion();
- }
- }
- class RedisServer_v1_2 extends RedisServerProfile {
- public function getVersion() { return '1.2'; }
- public function getSupportedCommands() {
- return array(
- /* ---------------- Redis 1.2 ---------------- */
- /* miscellaneous commands */
- 'ping' => '\Predis\Commands\Ping',
- 'echo' => '\Predis\Commands\DoEcho',
- 'auth' => '\Predis\Commands\Auth',
- /* connection handling */
- 'quit' => '\Predis\Commands\Quit',
- /* commands operating on string values */
- 'set' => '\Predis\Commands\Set',
- 'setnx' => '\Predis\Commands\SetPreserve',
- 'mset' => '\Predis\Commands\SetMultiple',
- 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
- 'get' => '\Predis\Commands\Get',
- 'mget' => '\Predis\Commands\GetMultiple',
- 'getset' => '\Predis\Commands\GetSet',
- 'incr' => '\Predis\Commands\Increment',
- 'incrby' => '\Predis\Commands\IncrementBy',
- 'decr' => '\Predis\Commands\Decrement',
- 'decrby' => '\Predis\Commands\DecrementBy',
- 'exists' => '\Predis\Commands\Exists',
- 'del' => '\Predis\Commands\Delete',
- 'type' => '\Predis\Commands\Type',
- /* commands operating on the key space */
- 'keys' => '\Predis\Commands\Keys_v1_2',
- 'randomkey' => '\Predis\Commands\RandomKey',
- 'rename' => '\Predis\Commands\Rename',
- 'renamenx' => '\Predis\Commands\RenamePreserve',
- 'expire' => '\Predis\Commands\Expire',
- 'expireat' => '\Predis\Commands\ExpireAt',
- 'dbsize' => '\Predis\Commands\DatabaseSize',
- 'ttl' => '\Predis\Commands\TimeToLive',
- /* commands operating on lists */
- 'rpush' => '\Predis\Commands\ListPushTail',
- 'lpush' => '\Predis\Commands\ListPushHead',
- 'llen' => '\Predis\Commands\ListLength',
- 'lrange' => '\Predis\Commands\ListRange',
- 'ltrim' => '\Predis\Commands\ListTrim',
- 'lindex' => '\Predis\Commands\ListIndex',
- 'lset' => '\Predis\Commands\ListSet',
- 'lrem' => '\Predis\Commands\ListRemove',
- 'lpop' => '\Predis\Commands\ListPopFirst',
- 'rpop' => '\Predis\Commands\ListPopLast',
- 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
- /* commands operating on sets */
- 'sadd' => '\Predis\Commands\SetAdd',
- 'srem' => '\Predis\Commands\SetRemove',
- 'spop' => '\Predis\Commands\SetPop',
- 'smove' => '\Predis\Commands\SetMove',
- 'scard' => '\Predis\Commands\SetCardinality',
- 'sismember' => '\Predis\Commands\SetIsMember',
- 'sinter' => '\Predis\Commands\SetIntersection',
- 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
- 'sunion' => '\Predis\Commands\SetUnion',
- 'sunionstore' => '\Predis\Commands\SetUnionStore',
- 'sdiff' => '\Predis\Commands\SetDifference',
- 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
- 'smembers' => '\Predis\Commands\SetMembers',
- 'srandmember' => '\Predis\Commands\SetRandomMember',
- /* commands operating on sorted sets */
- 'zadd' => '\Predis\Commands\ZSetAdd',
- 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
- 'zrem' => '\Predis\Commands\ZSetRemove',
- 'zrange' => '\Predis\Commands\ZSetRange',
- 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
- 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
- 'zcard' => '\Predis\Commands\ZSetCardinality',
- 'zscore' => '\Predis\Commands\ZSetScore',
- 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
- /* multiple databases handling commands */
- 'select' => '\Predis\Commands\SelectDatabase',
- 'move' => '\Predis\Commands\MoveKey',
- 'flushdb' => '\Predis\Commands\FlushDatabase',
- 'flushall' => '\Predis\Commands\FlushAll',
- /* sorting */
- 'sort' => '\Predis\Commands\Sort',
- /* remote server control commands */
- 'info' => '\Predis\Commands\Info',
- 'slaveof' => '\Predis\Commands\SlaveOf',
- /* persistence control commands */
- 'save' => '\Predis\Commands\Save',
- 'bgsave' => '\Predis\Commands\BackgroundSave',
- 'lastsave' => '\Predis\Commands\LastSave',
- 'shutdown' => '\Predis\Commands\Shutdown',
- 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
- );
- }
- }
- class RedisServer_v2_0 extends RedisServerProfile {
- public function getVersion() { return '2.0'; }
- public function getSupportedCommands() {
- return array(
- /* ---------------- Redis 1.2 ---------------- */
- /* miscellaneous commands */
- 'ping' => '\Predis\Commands\Ping',
- 'echo' => '\Predis\Commands\DoEcho',
- 'auth' => '\Predis\Commands\Auth',
- /* connection handling */
- 'quit' => '\Predis\Commands\Quit',
- /* commands operating on string values */
- 'set' => '\Predis\Commands\Set',
- 'setnx' => '\Predis\Commands\SetPreserve',
- 'mset' => '\Predis\Commands\SetMultiple',
- 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
- 'get' => '\Predis\Commands\Get',
- 'mget' => '\Predis\Commands\GetMultiple',
- 'getset' => '\Predis\Commands\GetSet',
- 'incr' => '\Predis\Commands\Increment',
- 'incrby' => '\Predis\Commands\IncrementBy',
- 'decr' => '\Predis\Commands\Decrement',
- 'decrby' => '\Predis\Commands\DecrementBy',
- 'exists' => '\Predis\Commands\Exists',
- 'del' => '\Predis\Commands\Delete',
- 'type' => '\Predis\Commands\Type',
- /* commands operating on the key space */
- 'keys' => '\Predis\Commands\Keys',
- 'randomkey' => '\Predis\Commands\RandomKey',
- 'rename' => '\Predis\Commands\Rename',
- 'renamenx' => '\Predis\Commands\RenamePreserve',
- 'expire' => '\Predis\Commands\Expire',
- 'expireat' => '\Predis\Commands\ExpireAt',
- 'dbsize' => '\Predis\Commands\DatabaseSize',
- 'ttl' => '\Predis\Commands\TimeToLive',
- /* commands operating on lists */
- 'rpush' => '\Predis\Commands\ListPushTail',
- 'lpush' => '\Predis\Commands\ListPushHead',
- 'llen' => '\Predis\Commands\ListLength',
- 'lrange' => '\Predis\Commands\ListRange',
- 'ltrim' => '\Predis\Commands\ListTrim',
- 'lindex' => '\Predis\Commands\ListIndex',
- 'lset' => '\Predis\Commands\ListSet',
- 'lrem' => '\Predis\Commands\ListRemove',
- 'lpop' => '\Predis\Commands\ListPopFirst',
- 'rpop' => '\Predis\Commands\ListPopLast',
- 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
- /* commands operating on sets */
- 'sadd' => '\Predis\Commands\SetAdd',
- 'srem' => '\Predis\Commands\SetRemove',
- 'spop' => '\Predis\Commands\SetPop',
- 'smove' => '\Predis\Commands\SetMove',
- 'scard' => '\Predis\Commands\SetCardinality',
- 'sismember' => '\Predis\Commands\SetIsMember',
- 'sinter' => '\Predis\Commands\SetIntersection',
- 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
- 'sunion' => '\Predis\Commands\SetUnion',
- 'sunionstore' => '\Predis\Commands\SetUnionStore',
- 'sdiff' => '\Predis\Commands\SetDifference',
- 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
- 'smembers' => '\Predis\Commands\SetMembers',
- 'srandmember' => '\Predis\Commands\SetRandomMember',
- /* commands operating on sorted sets */
- 'zadd' => '\Predis\Commands\ZSetAdd',
- 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
- 'zrem' => '\Predis\Commands\ZSetRemove',
- 'zrange' => '\Predis\Commands\ZSetRange',
- 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
- 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
- 'zcard' => '\Predis\Commands\ZSetCardinality',
- 'zscore' => '\Predis\Commands\ZSetScore',
- 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
- /* multiple databases handling commands */
- 'select' => '\Predis\Commands\SelectDatabase',
- 'move' => '\Predis\Commands\MoveKey',
- 'flushdb' => '\Predis\Commands\FlushDatabase',
- 'flushall' => '\Predis\Commands\FlushAll',
- /* sorting */
- 'sort' => '\Predis\Commands\Sort',
- /* remote server control commands */
- 'info' => '\Predis\Commands\Info',
- 'slaveof' => '\Predis\Commands\SlaveOf',
- /* persistence control commands */
- 'save' => '\Predis\Commands\Save',
- 'bgsave' => '\Predis\Commands\BackgroundSave',
- 'lastsave' => '\Predis\Commands\LastSave',
- 'shutdown' => '\Predis\Commands\Shutdown',
- 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
- /* ---------------- Redis 2.0 ---------------- */
- /* transactions */
- 'multi' => '\Predis\Commands\Multi',
- 'exec' => '\Predis\Commands\Exec',
- 'discard' => '\Predis\Commands\Discard',
- /* commands operating on string values */
- 'setex' => '\Predis\Commands\SetExpire',
- 'append' => '\Predis\Commands\Append',
- 'substr' => '\Predis\Commands\Substr',
- /* commands operating on lists */
- 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
- 'brpop' => '\Predis\Commands\ListPopLastBlocking',
- /* commands operating on sorted sets */
- 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
- 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
- 'zcount' => '\Predis\Commands\ZSetCount',
- 'zrank' => '\Predis\Commands\ZSetRank',
- 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
- 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
- /* commands operating on hashes */
- 'hset' => '\Predis\Commands\HashSet',
- 'hsetnx' => '\Predis\Commands\HashSetPreserve',
- 'hmset' => '\Predis\Commands\HashSetMultiple',
- 'hincrby' => '\Predis\Commands\HashIncrementBy',
- 'hget' => '\Predis\Commands\HashGet',
- 'hmget' => '\Predis\Commands\HashGetMultiple',
- 'hdel' => '\Predis\Commands\HashDelete',
- 'hexists' => '\Predis\Commands\HashExists',
- 'hlen' => '\Predis\Commands\HashLength',
- 'hkeys' => '\Predis\Commands\HashKeys',
- 'hvals' => '\Predis\Commands\HashValues',
- 'hgetall' => '\Predis\Commands\HashGetAll',
- /* publish - subscribe */
- 'subscribe' => '\Predis\Commands\Subscribe',
- 'unsubscribe' => '\Predis\Commands\Unsubscribe',
- 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
- 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
- 'publish' => '\Predis\Commands\Publish',
- /* remote server control commands */
- 'config' => '\Predis\Commands\Config',
- );
- }
- }
- class RedisServer_v2_2 extends RedisServerProfile {
- public function getVersion() { return '2.2'; }
- public function getSupportedCommands() {
- return array(
- /* ---------------- Redis 1.2 ---------------- */
- /* miscellaneous commands */
- 'ping' => '\Predis\Commands\Ping',
- 'echo' => '\Predis\Commands\DoEcho',
- 'auth' => '\Predis\Commands\Auth',
- /* connection handling */
- 'quit' => '\Predis\Commands\Quit',
- /* commands operating on string values */
- 'set' => '\Predis\Commands\Set',
- 'setnx' => '\Predis\Commands\SetPreserve',
- 'mset' => '\Predis\Commands\SetMultiple',
- 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
- 'get' => '\Predis\Commands\Get',
- 'mget' => '\Predis\Commands\GetMultiple',
- 'getset' => '\Predis\Commands\GetSet',
- 'incr' => '\Predis\Commands\Increment',
- 'incrby' => '\Predis\Commands\IncrementBy',
- 'decr' => '\Predis\Commands\Decrement',
- 'decrby' => '\Predis\Commands\DecrementBy',
- 'exists' => '\Predis\Commands\Exists',
- 'del' => '\Predis\Commands\Delete',
- 'type' => '\Predis\Commands\Type',
- /* commands operating on the key space */
- 'keys' => '\Predis\Commands\Keys',
- 'randomkey' => '\Predis\Commands\RandomKey',
- 'rename' => '\Predis\Commands\Rename',
- 'renamenx' => '\Predis\Commands\RenamePreserve',
- 'expire' => '\Predis\Commands\Expire',
- 'expireat' => '\Predis\Commands\ExpireAt',
- 'dbsize' => '\Predis\Commands\DatabaseSize',
- 'ttl' => '\Predis\Commands\TimeToLive',
- /* commands operating on lists */
- 'rpush' => '\Predis\Commands\ListPushTail',
- 'lpush' => '\Predis\Commands\ListPushHead',
- 'llen' => '\Predis\Commands\ListLength',
- 'lrange' => '\Predis\Commands\ListRange',
- 'ltrim' => '\Predis\Commands\ListTrim',
- 'lindex' => '\Predis\Commands\ListIndex',
- 'lset' => '\Predis\Commands\ListSet',
- 'lrem' => '\Predis\Commands\ListRemove',
- 'lpop' => '\Predis\Commands\ListPopFirst',
- 'rpop' => '\Predis\Commands\ListPopLast',
- 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
- /* commands operating on sets */
- 'sadd' => '\Predis\Commands\SetAdd',
- 'srem' => '\Predis\Commands\SetRemove',
- 'spop' => '\Predis\Commands\SetPop',
- 'smove' => '\Predis\Commands\SetMove',
- 'scard' => '\Predis\Commands\SetCardinality',
- 'sismember' => '\Predis\Commands\SetIsMember',
- 'sinter' => '\Predis\Commands\SetIntersection',
- 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
- 'sunion' => '\Predis\Commands\SetUnion',
- 'sunionstore' => '\Predis\Commands\SetUnionStore',
- 'sdiff' => '\Predis\Commands\SetDifference',
- 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
- 'smembers' => '\Predis\Commands\SetMembers',
- 'srandmember' => '\Predis\Commands\SetRandomMember',
- /* commands operating on sorted sets */
- 'zadd' => '\Predis\Commands\ZSetAdd',
- 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
- 'zrem' => '\Predis\Commands\ZSetRemove',
- 'zrange' => '\Predis\Commands\ZSetRange',
- 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
- 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
- 'zcard' => '\Predis\Commands\ZSetCardinality',
- 'zscore' => '\Predis\Commands\ZSetScore',
- 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
- /* multiple databases handling commands */
- 'select' => '\Predis\Commands\SelectDatabase',
- 'move' => '\Predis\Commands\MoveKey',
- 'flushdb' => '\Predis\Commands\FlushDatabase',
- 'flushall' => '\Predis\Commands\FlushAll',
- /* sorting */
- 'sort' => '\Predis\Commands\Sort',
- /* remote server control commands */
- 'info' => '\Predis\Commands\Info',
- 'slaveof' => '\Predis\Commands\SlaveOf',
- /* persistence control commands */
- 'save' => '\Predis\Commands\Save',
- 'bgsave' => '\Predis\Commands\BackgroundSave',
- 'lastsave' => '\Predis\Commands\LastSave',
- 'shutdown' => '\Predis\Commands\Shutdown',
- 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
- /* ---------------- Redis 2.0 ---------------- */
- /* transactions */
- 'multi' => '\Predis\Commands\Multi',
- 'exec' => '\Predis\Commands\Exec',
- 'discard' => '\Predis\Commands\Discard',
- /* commands operating on string values */
- 'setex' => '\Predis\Commands\SetExpire',
- 'append' => '\Predis\Commands\Append',
- 'substr' => '\Predis\Commands\Substr',
- /* commands operating on lists */
- 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
- 'brpop' => '\Predis\Commands\ListPopLastBlocking',
- /* commands operating on sorted sets */
- 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
- 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
- 'zcount' => '\Predis\Commands\ZSetCount',
- 'zrank' => '\Predis\Commands\ZSetRank',
- 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
- 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
- /* commands operating on hashes */
- 'hset' => '\Predis\Commands\HashSet',
- 'hsetnx' => '\Predis\Commands\HashSetPreserve',
- 'hmset' => '\Predis\Commands\HashSetMultiple',
- 'hincrby' => '\Predis\Commands\HashIncrementBy',
- 'hget' => '\Predis\Commands\HashGet',
- 'hmget' => '\Predis\Commands\HashGetMultiple',
- 'hdel' => '\Predis\Commands\HashDelete',
- 'hexists' => '\Predis\Commands\HashExists',
- 'hlen' => '\Predis\Commands\HashLength',
- 'hkeys' => '\Predis\Commands\HashKeys',
- 'hvals' => '\Predis\Commands\HashValues',
- 'hgetall' => '\Predis\Commands\HashGetAll',
- /* publish - subscribe */
- 'subscribe' => '\Predis\Commands\Subscribe',
- 'unsubscribe' => '\Predis\Commands\Unsubscribe',
- 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
- 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
- 'publish' => '\Predis\Commands\Publish',
- /* remote server control commands */
- 'config' => '\Predis\Commands\Config',
- /* ---------------- Redis 2.2 ---------------- */
- /* transactions */
- 'watch' => '\Predis\Commands\Watch',
- 'unwatch' => '\Predis\Commands\Unwatch',
- /* commands operating on string values */
- 'strlen' => '\Predis\Commands\Strlen',
- 'setrange' => '\Predis\Commands\SetRange',
- 'getrange' => '\Predis\Commands\Substr',
- 'setbit' => '\Predis\Commands\SetBit',
- 'getbit' => '\Predis\Commands\GetBit',
- /* commands operating on the key space */
- 'persist' => '\Predis\Commands\Persist',
- /* commands operating on lists */
- 'rpushx' => '\Predis\Commands\ListPushTailX',
- 'lpushx' => '\Predis\Commands\ListPushHeadX',
- 'linsert' => '\Predis\Commands\ListInsert',
- 'brpoplpush' => '\Predis\Commands\ListPopLastPushHeadBlocking',
- /* commands operating on sorted sets */
- 'zrevrangebyscore' => '\Predis\Commands\ZSetReverseRangeByScore',
- );
- }
- }
- class RedisServer_vNext extends RedisServer_v2_2 {
- public function getVersion() { return 'DEV'; }
- public function getSupportedCommands() {
- return array_merge(parent::getSupportedCommands(), array(
- /* remote server control commands */
- 'info' => '\Predis\Commands\Info_v24',
- ));
- }
- }
- /* ------------------------------------------------------------------------- */
- namespace Predis\Pipeline;
- interface IPipelineExecutor {
- public function execute(\Predis\IConnection $connection, &$commands);
- }
- class StandardExecutor implements IPipelineExecutor {
- public function execute(\Predis\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]);
- $values[] = $response instanceof \Iterator
- ? iterator_to_array($response)
- : $response;
- unset($commands[$i]);
- }
- }
- catch (\Predis\ServerException $exception) {
- // force disconnection to prevent protocol desynchronization
- $connection->disconnect();
- throw $exception;
- }
- return $values;
- }
- }
- class SafeExecutor implements IPipelineExecutor {
- public function execute(\Predis\IConnection $connection, &$commands) {
- $sizeofPipe = count($commands);
- $values = array();
- foreach ($commands as $command) {
- try {
- $connection->writeCommand($command);
- }
- catch (\Predis\CommunicationException $exception) {
- return array_fill(0, $sizeofPipe, $exception);
- }
- }
- 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
- );
- }
- catch (\Predis\ServerException $exception) {
- $values[] = $exception->toResponseError();
- }
- catch (\Predis\CommunicationException $exception) {
- $toAdd = count($commands) - count($values);
- $values = array_merge($values, array_fill(0, $toAdd, $exception));
- break;
- }
- }
- return $values;
- }
- }
- class SafeClusterExecutor implements IPipelineExecutor {
- public function execute(\Predis\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);
- }
- catch (\Predis\CommunicationException $exception) {
- $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
- }
- }
- for ($i = 0; $i < $sizeofPipe; $i++) {
- $command = $commands[$i];
- unset($commands[$i]);
- $cmdConnection = $connection->getConnection($command);
- $connectionObjectHash = spl_object_hash($cmdConnection);
- if (isset($connectionExceptions[$connectionObjectHash])) {
- $values[] = $connectionExceptions[$connectionObjectHash];
- continue;
- }
- try {
- $response = $cmdConnection->readResponse($command);
- $values[] = ($response instanceof \Iterator
- ? iterator_to_array($response)
- : $response
- );
- }
- catch (\Predis\ServerException $exception) {
- $values[] = $exception->toResponseError();
- }
- catch (\Predis\CommunicationException $exception) {
- $values[] = $exception;
- $connectionExceptions[$connectionObjectHash] = $exception;
- }
- }
- return $values;
- }
- }
- /* ------------------------------------------------------------------------- */
- namespace Predis\Distribution;
- interface IDistributionStrategy {
- public function add($node, $weight = null);
- public function remove($node);
- public function get($key);
- public function generateKey($value);
- }
- class EmptyRingException extends \Exception { }
- class HashRing implements IDistributionStrategy {
- const DEFAULT_REPLICAS = 128;
- const DEFAULT_WEIGHT = 100;
- private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
- public function __construct($replicas = self::DEFAULT_REPLICAS) {
- $this->_replicas = $replicas;
- $this->_nodes = array();
- }
- public function add($node, $weight = null) {
- // NOTE: 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) {
- // NOTE: 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
- // first place.
- for ($i = 0; $i < count($this->_nodes); ++$i) {
- if ($this->_nodes[$i]['object'] === $node) {
- array_splice($this->_nodes, $i, 1);
- $this->reset();
- break;
- }
- }
- }
- private function reset() {
- unset($this->_ring);
- unset($this->_ringKeys);
- unset($this->_ringKeysCount);
- }
- private function isInitialized() {
- return isset($this->_ringKeys);
- }
- private function computeTotalWeight() {
- // TODO: array_reduce + lambda for PHP 5.3
- $totalWeight = 0;
- foreach ($this->_nodes as $node) {
- $totalWeight += $node['weight'];
- }
- return $totalWeight;
- }
- private function initialize() {
- if ($this->isInitialized()) {
- return;
- }
- if (count($this->_nodes) === 0) {
- throw new EmptyRingException('Cannot initialize empty hashring');
- }
- $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) {
- $nodeObject = $node['object'];
- $nodeHash = (string) $nodeObject;
- $replicas = (int) round($weightRatio * $totalNodes * $replicas);
- for ($i = 0; $i < $replicas; $i++) {
- $key = crc32("$nodeHash:$i");
- $ring[$key] = $nodeObject;
- }
- }
- public function generateKey($value) {
- return crc32($value);
- }
- public function get($key) {
- return $this->_ring[$this->getNodeKey($key)];
- }
- private function getNodeKey($key) {
- $this->initialize();
- $ringKeys = $this->_ringKeys;
- $upper = $this->_ringKeysCount - 1;
- $lower = 0;
- while ($lower <= $upper) {
- $index = ($lower + $upper) >> 1;
- $item = $ringKeys[$index];
- if ($item > $key) {
- $upper = $index - 1;
- }
- else if ($item < $key) {
- $lower = $index + 1;
- }
- else {
- return $item;
- }
- }
- return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
- }
- protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
- // NOTE: 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;
- }
- }
- class KetamaPureRing extends HashRing {
- const DEFAULT_REPLICAS = 160;
- public function __construct() {
- parent::__construct($this::DEFAULT_REPLICAS);
- }
- protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
- $nodeObject = $node['object'];
- $nodeHash = (string) $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) {
- $ring[$key] = $nodeObject;
- }
- }
- }
- public function generateKey($value) {
- $hash = unpack('V', md5($value, true));
- return $hash[1];
- }
- protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
- // NOTE: 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;
- }
- }
- /* ------------------------------------------------------------------------- */
- namespace Predis\Shared;
- class Utils {
- public static function isCluster(\Predis\IConnection $connection) {
- return $connection instanceof \Predis\ConnectionCluster;
- }
- public static function onCommunicationException(\Predis\CommunicationException $exception) {
- if ($exception->shouldResetConnection()) {
- $connection = $exception->getConnection();
- if ($connection->isConnected()) {
- $connection->disconnect();
- }
- }
- throw $exception;
- }
- public static function filterArrayArguments(Array $arguments) {
- if (count($arguments) === 1 && is_array($arguments[0])) {
- return $arguments[0];
- }
- return $arguments;
- }
- }
- abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
- protected $_position, $_current, $_replySize;
- public function rewind() {
- // NOOP
- }
- public function current() {
- return $this->_current;
- }
- public function key() {
- return $this->_position;
- }
- public function next() {
- if (++$this->_position < $this->_replySize) {
- $this->_current = $this->getValue();
- }
- return $this->_position;
- }
- public function valid() {
- return $this->_position < $this->_replySize;
- }
- public function count() {
- // NOTE: 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)
- return $this->_replySize;
- }
- protected abstract function getValue();
- }
- class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
- private $_connection;
- public function __construct(\Predis\Connection $connection, $size) {
- $this->_connection = $connection;
- $this->_reader = $connection->getResponseReader();
- $this->_position = 0;
- $this->_current = $size > 0 ? $this->getValue() : null;
- $this->_replySize = $size;
- }
- 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
- // the connection with the server.
- $this->sync();
- }
- public function sync($drop = false) {
- if ($drop == true) {
- if ($this->valid()) {
- $this->_position = $this->_replySize;
- $this->_connection->disconnect();
- }
- }
- else {
- while ($this->valid()) {
- $this->next();
- }
- }
- }
- protected function getValue() {
- return $this->_reader->read($this->_connection);
- }
- }
- class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
- private $_iterator;
- public function __construct(MultiBulkResponseIterator $iterator) {
- $virtualSize = count($iterator) / 2;
- $this->_iterator = $iterator;
- $this->_position = 0;
- $this->_current = $virtualSize > 0 ? $this->getValue() : null;
- $this->_replySize = $virtualSize;
- }
- public function __destruct() {
- $this->_iterator->sync();
- }
- protected function getValue() {
- $k = $this->_iterator->current();
- $this->_iterator->next();
- $v = $this->_iterator->current();
- $this->_iterator->next();
- return array($k, $v);
- }
- }
- /* ------------------------------------------------------------------------- */
- namespace Predis\Commands;
- /* miscellaneous commands */
- class Ping extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'PING'; }
- public function parseResponse($data) {
- return $data === 'PONG';
- }
- }
- class DoEcho extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'ECHO'; }
- }
- class Auth extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'AUTH'; }
- }
- /* connection handling */
- class Quit extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'QUIT'; }
- public function closesConnection() { return true; }
- }
- /* commands operating on string values */
- class Set extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SET'; }
- }
- class SetExpire extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SETEX'; }
- }
- class SetPreserve extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SETNX'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class SetMultiple extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'MSET'; }
- public 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;
- }
- }
- class SetMultiplePreserve extends \Predis\Commands\SetMultiple {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'MSETNX'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class Get extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'GET'; }
- }
- class GetMultiple extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'MGET'; }
- public function filterArguments(Array $arguments) {
- return \Predis\Shared\Utils::filterArrayArguments($arguments);
- }
- }
- class GetSet extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'GETSET'; }
- }
- class Increment extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'INCR'; }
- }
- class IncrementBy extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'INCRBY'; }
- }
- class Decrement extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'DECR'; }
- }
- class DecrementBy extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'DECRBY'; }
- }
- class Exists extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'EXISTS'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class Delete extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'DEL'; }
- }
- class Type extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'TYPE'; }
- }
- class Append extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'APPEND'; }
- }
- class SetRange extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SETRANGE'; }
- }
- class Substr extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SUBSTR'; }
- }
- class SetBit extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SETBIT'; }
- }
- class GetBit extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'GETBIT'; }
- }
- class Strlen extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'STRLEN'; }
- }
- /* commands operating on the key space */
- class Keys extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'KEYS'; }
- }
- class Keys_v1_2 extends Keys {
- public function parseResponse($data) {
- return explode(' ', $data);
- }
- }
- class RandomKey extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'RANDOMKEY'; }
- public function parseResponse($data) { return $data !== '' ? $data : null; }
- }
- class Rename extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'RENAME'; }
- }
- class RenamePreserve extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'RENAMENX'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class Expire extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'EXPIRE'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class ExpireAt extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'EXPIREAT'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class Persist extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'PERSIST'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class DatabaseSize extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'DBSIZE'; }
- }
- class TimeToLive extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'TTL'; }
- }
- /* commands operating on lists */
- class ListPushTail extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'RPUSH'; }
- }
- class ListPushTailX extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'RPUSHX'; }
- }
- class ListPushHead extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LPUSH'; }
- }
- class ListPushHeadX extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LPUSHX'; }
- }
- class ListLength extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LLEN'; }
- }
- class ListRange extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LRANGE'; }
- }
- class ListTrim extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LTRIM'; }
- }
- class ListIndex extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LINDEX'; }
- }
- class ListSet extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LSET'; }
- }
- class ListRemove extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LREM'; }
- }
- class ListPopLastPushHead extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'RPOPLPUSH'; }
- }
- class ListPopLastPushHeadBlocking extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'BRPOPLPUSH'; }
- }
- class ListPopFirst extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LPOP'; }
- }
- class ListPopLast extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'RPOP'; }
- }
- class ListPopFirstBlocking extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'BLPOP'; }
- }
- class ListPopLastBlocking extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'BRPOP'; }
- }
- class ListInsert extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'LINSERT'; }
- }
- /* commands operating on sets */
- class SetAdd extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SADD'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class SetRemove extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SREM'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class SetPop extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SPOP'; }
- }
- class SetMove extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'SMOVE'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class SetCardinality extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SCARD'; }
- }
- class SetIsMember extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SISMEMBER'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class SetIntersection extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SINTER'; }
- public function filterArguments(Array $arguments) {
- return \Predis\Shared\Utils::filterArrayArguments($arguments);
- }
- }
- class SetIntersectionStore extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SINTERSTORE'; }
- public function filterArguments(Array $arguments) {
- if (count($arguments) === 2 && is_array($arguments[1])) {
- return array_merge(array($arguments[0]), $arguments[1]);
- }
- return $arguments;
- }
- }
- class SetUnion extends \Predis\Commands\SetIntersection {
- public function getCommandId() { return 'SUNION'; }
- }
- class SetUnionStore extends \Predis\Commands\SetIntersectionStore {
- public function getCommandId() { return 'SUNIONSTORE'; }
- }
- class SetDifference extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SDIFF'; }
- }
- class SetDifferenceStore extends \Predis\Commands\SetIntersectionStore {
- public function getCommandId() { return 'SDIFFSTORE'; }
- }
- class SetMembers extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SMEMBERS'; }
- }
- class SetRandomMember extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SRANDMEMBER'; }
- }
- /* commands operating on sorted sets */
- class ZSetAdd extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZADD'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class ZSetIncrementBy extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZINCRBY'; }
- }
- class ZSetRemove extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZREM'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class ZSetUnionStore extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZUNIONSTORE'; }
- public 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) {
- $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;
- }
- }
- class ZSetIntersectionStore extends \Predis\Commands\ZSetUnionStore {
- public function getCommandId() { return 'ZINTERSTORE'; }
- }
- class ZSetRange extends \Predis\MultiBulkCommand {
- private $_withScores = false;
- public function getCommandId() { return 'ZRANGE'; }
- public 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) {
- $opts = array_change_key_case($options, CASE_UPPER);
- $finalizedOpts = array();
- if (isset($opts['WITHSCORES'])) {
- $finalizedOpts[] = 'WITHSCORES';
- $this->_withScores = true;
- }
- return $finalizedOpts;
- }
- public function parseResponse($data) {
- if ($this->_withScores) {
- if ($data instanceof \Iterator) {
- return new \Predis\Shared\MultiBulkResponseKVIterator($data);
- }
- $result = array();
- for ($i = 0; $i < count($data); $i++) {
- $result[] = array($data[$i], $data[++$i]);
- }
- return $result;
- }
- return $data;
- }
- }
- class ZSetReverseRange extends \Predis\Commands\ZSetRange {
- public function getCommandId() { return 'ZREVRANGE'; }
- }
- class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
- public function getCommandId() { return 'ZRANGEBYSCORE'; }
- 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));
- }
- }
- class ZSetReverseRangeByScore extends \Predis\Commands\ZSetRangeByScore {
- public function getCommandId() { return 'ZREVRANGEBYSCORE'; }
- }
- class ZSetCount extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZCOUNT'; }
- }
- class ZSetCardinality extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZCARD'; }
- }
- class ZSetScore extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZSCORE'; }
- }
- class ZSetRemoveRangeByScore extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
- }
- class ZSetRank extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZRANK'; }
- }
- class ZSetReverseRank extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZREVRANK'; }
- }
- class ZSetRemoveRangeByRank extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'ZREMRANGEBYRANK'; }
- }
- /* commands operating on hashes */
- class HashSet extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HSET'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class HashSetPreserve extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HSETNX'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class HashSetMultiple extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HMSET'; }
- public 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;
- }
- }
- class HashIncrementBy extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HINCRBY'; }
- }
- class HashGet extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HGET'; }
- }
- class HashGetMultiple extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HMGET'; }
- public function filterArguments(Array $arguments) {
- if (count($arguments) === 2 && is_array($arguments[1])) {
- $flattenedKVs = array($arguments[0]);
- $args = &$arguments[1];
- foreach ($args as $v) {
- $flattenedKVs[] = $v;
- }
- return $flattenedKVs;
- }
- return $arguments;
- }
- }
- class HashDelete extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HDEL'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class HashExists extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HEXISTS'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class HashLength extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HLEN'; }
- }
- class HashKeys extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HKEYS'; }
- }
- class HashValues extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HVALS'; }
- }
- class HashGetAll extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'HGETALL'; }
- public function parseResponse($data) {
- if ($data instanceof \Iterator) {
- return new \Predis\Shared\MultiBulkResponseKVIterator($data);
- }
- $result = array();
- for ($i = 0; $i < count($data); $i++) {
- $result[$data[$i]] = $data[++$i];
- }
- return $result;
- }
- }
- /* multiple databases handling commands */
- class SelectDatabase extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'SELECT'; }
- }
- class MoveKey extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'MOVE'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- class FlushDatabase extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'FLUSHDB'; }
- }
- class FlushAll extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'FLUSHALL'; }
- }
- /* sorting */
- class Sort extends \Predis\MultiBulkCommand {
- public function getCommandId() { return 'SORT'; }
- public function filterArguments(Array $arguments) {
- if (count($arguments) === 1) {
- return $arguments;
- }
- $query = array($arguments[0]);
- $sortParams = array_change_key_case($arguments[1], CASE_UPPER);
- if (isset($sortParams['BY'])) {
- $query[] = 'BY';
- $query[] = $sortParams['BY'];
- }
- if (isset($sortParams['GET'])) {
- $getargs = $sortParams['GET'];
- if (is_array($getargs)) {
- foreach ($getargs as $getarg) {
- $query[] = 'GET';
- $query[] = $getarg;
- }
- }
- else {
- $query[] = 'GET';
- $query[] = $getargs;
- }
- }
- if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
- && count($sortParams['LIMIT']) == 2) {
- $query[] = 'LIMIT';
- $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'];
- }
- return $query;
- }
- }
- /* transactions */
- class Multi extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'MULTI'; }
- }
- class Exec extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'EXEC'; }
- }
- class Discard extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'DISCARD'; }
- }
- class Watch extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'WATCH'; }
- public function filterArguments(Array $arguments) {
- if (isset($arguments[0]) && is_array($arguments[0])) {
- return $arguments[0];
- }
- return $arguments;
- }
- public function parseResponse($data) { return (bool) $data; }
- }
- class Unwatch extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'UNWATCH'; }
- public function parseResponse($data) { return (bool) $data; }
- }
- /* publish/subscribe */
- class Subscribe extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'SUBSCRIBE'; }
- public function filterArguments(Array $arguments) {
- return \Predis\Shared\Utils::filterArrayArguments($arguments);
- }
- }
- class Unsubscribe extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'UNSUBSCRIBE'; }
- }
- class SubscribeByPattern extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'UNSUBSCRIBE'; }
- public function filterArguments(Array $arguments) {
- return \Predis\Shared\Utils::filterArrayArguments($arguments);
- }
- }
- class UnsubscribeByPattern extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'PUNSUBSCRIBE'; }
- }
- class Publish extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'PUBLISH'; }
- }
- /* persistence control commands */
- class Save extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'SAVE'; }
- }
- class BackgroundSave extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'BGSAVE'; }
- public function parseResponse($data) {
- if ($data == 'Background saving started') {
- return true;
- }
- return $data;
- }
- }
- class BackgroundRewriteAppendOnlyFile extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'BGREWRITEAOF'; }
- public function parseResponse($data) {
- return $data == 'Background append only file rewriting started';
- }
- }
- class LastSave extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'LASTSAVE'; }
- }
- class Shutdown extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'SHUTDOWN'; }
- public function closesConnection() { return true; }
- }
- /* remote server control commands */
- class Info extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'INFO'; }
- 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);
- continue;
- }
- $info[$k] = $v;
- }
- else {
- $info[$k] = $this->parseDatabaseStats($v);
- }
- }
- return $info;
- }
- 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) {
- $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";
- $objects = $extra;
- }
- $stats[$size] = $objects;
- }
- return $stats;
- }
- }
- class Info_v24 extends Info {
- 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);
- continue;
- }
- $current[$k] = $v;
- }
- else {
- $current[$k] = $this->parseDatabaseStats($v);
- }
- }
- return $info;
- }
- }
- class SlaveOf extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'SLAVEOF'; }
- public function filterArguments(Array $arguments) {
- if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
- return array('NO', 'ONE');
- }
- return $arguments;
- }
- }
- class Config extends \Predis\MultiBulkCommand {
- public function canBeHashed() { return false; }
- public function getCommandId() { return 'CONFIG'; }
- }
- ?>
|