Predis.php 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041
  1. <?php
  2. namespace Predis;
  3. use Predis\Shared\Utils, Predis\Distribution\IDistributionStrategy;
  4. class PredisException extends \Exception { }
  5. class ClientException extends PredisException { } // Client-side errors
  6. class AbortedMultiExec extends PredisException { } // Aborted multi/exec
  7. class ServerException extends PredisException { // Server-side errors
  8. public function toResponseError() {
  9. return new ResponseError($this->getMessage());
  10. }
  11. }
  12. class CommunicationException extends PredisException { // Communication errors
  13. private $_connection;
  14. public function __construct(IConnectionSingle $connection,
  15. $message = null, $code = null) {
  16. $this->_connection = $connection;
  17. parent::__construct($message, $code);
  18. }
  19. public function getConnection() { return $this->_connection; }
  20. public function shouldResetConnection() { return true; }
  21. }
  22. class MalformedServerResponse extends CommunicationException { } // Unexpected responses
  23. /* ------------------------------------------------------------------------- */
  24. class Client {
  25. private $_options, $_connection, $_serverProfile, $_responseReader;
  26. public function __construct($parameters = null, $clientOptions = null) {
  27. $this->setupClient($clientOptions ?: new ClientOptions());
  28. $this->setupConnection($parameters);
  29. }
  30. private static function filterClientOptions($options) {
  31. if ($options instanceof ClientOptions) {
  32. return $options;
  33. }
  34. if (is_array($options)) {
  35. return new ClientOptions($options);
  36. }
  37. if ($options instanceof RedisServerProfile) {
  38. return new ClientOptions(array(
  39. 'profile' => $options
  40. ));
  41. }
  42. if (is_string($options)) {
  43. return new ClientOptions(array(
  44. 'profile' => RedisServerProfile::get($options)
  45. ));
  46. }
  47. throw new \InvalidArgumentException("Invalid type for client options");
  48. }
  49. private function setupClient($options) {
  50. $this->_responseReader = new ResponseReader();
  51. $this->_options = self::filterClientOptions($options);
  52. $this->setProfile($this->_options->profile);
  53. if ($this->_options->iterable_multibulk === true) {
  54. $this->_responseReader->setHandler(
  55. Protocol::PREFIX_MULTI_BULK,
  56. new ResponseMultiBulkStreamHandler()
  57. );
  58. }
  59. if ($this->_options->throw_on_error === false) {
  60. $this->_responseReader->setHandler(
  61. Protocol::PREFIX_ERROR,
  62. new ResponseErrorSilentHandler()
  63. );
  64. }
  65. }
  66. private function setupConnection($parameters) {
  67. if ($parameters === null) {
  68. return $this->setConnection($this->createConnection(null));
  69. }
  70. if (!(is_array($parameters) || is_string($parameters) || $parameters instanceof IConnection
  71. || $parameters instanceof ConnectionParameters)) {
  72. throw new \InvalidArgumentException(
  73. 'Array, String, Predis\ConnectionParameters or Predis\IConnection expected'
  74. );
  75. }
  76. if (is_array($parameters) && isset($parameters[0])) {
  77. $cluster = new ConnectionCluster($this->_options->key_distribution);
  78. foreach ($parameters as $shardParams) {
  79. $cluster->add($this->createConnection($shardParams));
  80. }
  81. $this->setConnection($cluster);
  82. }
  83. else if ($parameters instanceof IConnectionCluster) {
  84. $this->setConnection($parameters);
  85. }
  86. else {
  87. $this->setConnection($this->createConnection($parameters));
  88. }
  89. }
  90. private function createConnection($parameters) {
  91. $params = null;
  92. $connection = null;
  93. if ($parameters instanceof IConnectionSingle) {
  94. $connection = $parameters;
  95. $params = $connection->getParameters();
  96. }
  97. else {
  98. $params = $parameters instanceof ConnectionParameters
  99. ? $parameters
  100. : new ConnectionParameters($parameters);
  101. $connection = ConnectionFactory::create($params, $this->_responseReader);
  102. }
  103. return $this->pushInitCommands($connection, $params);
  104. }
  105. private function pushInitCommands(IConnectionSingle $connection, ConnectionParameters $params) {
  106. if (isset($params->password)) {
  107. $connection->pushInitCommand($this->createCommand(
  108. 'auth', array($params->password)
  109. ));
  110. }
  111. if (isset($params->database)) {
  112. $connection->pushInitCommand($this->createCommand(
  113. 'select', array($params->database)
  114. ));
  115. }
  116. return $connection;
  117. }
  118. private function setConnection(IConnection $connection) {
  119. $this->_connection = $connection;
  120. }
  121. private function setProfile($serverProfile) {
  122. if (!($serverProfile instanceof RedisServerProfile || is_string($serverProfile))) {
  123. throw new \InvalidArgumentException(
  124. "Invalid type for server profile, \Predis\RedisServerProfile or string expected"
  125. );
  126. }
  127. $this->_serverProfile = (is_string($serverProfile)
  128. ? RedisServerProfile::get($serverProfile)
  129. : $serverProfile
  130. );
  131. }
  132. public function getProfile() {
  133. return $this->_serverProfile;
  134. }
  135. public function getResponseReader() {
  136. return $this->_responseReader;
  137. }
  138. public function getClientFor($connectionAlias) {
  139. if (!Utils::isCluster($this->_connection)) {
  140. throw new ClientException(
  141. 'This method is supported only when the client is connected to a cluster of connections'
  142. );
  143. }
  144. $connection = $this->_connection->getConnectionById($connectionAlias);
  145. if ($connection === null) {
  146. throw new \InvalidArgumentException(
  147. "Invalid connection alias: '$connectionAlias'"
  148. );
  149. }
  150. $newClient = new Client();
  151. $newClient->setupClient($this->_options);
  152. $newClient->setConnection($connection);
  153. return $newClient;
  154. }
  155. public function connect() {
  156. $this->_connection->connect();
  157. }
  158. public function disconnect() {
  159. $this->_connection->disconnect();
  160. }
  161. public function isConnected() {
  162. return $this->_connection->isConnected();
  163. }
  164. public function getConnection($id = null) {
  165. if (!isset($id)) {
  166. return $this->_connection;
  167. }
  168. else {
  169. return Utils::isCluster($this->_connection)
  170. ? $this->_connection->getConnectionById($id)
  171. : $this->_connection;
  172. }
  173. }
  174. public function __call($method, $arguments) {
  175. $command = $this->_serverProfile->createCommand($method, $arguments);
  176. return $this->_connection->executeCommand($command);
  177. }
  178. public function createCommand($method, $arguments = array()) {
  179. return $this->_serverProfile->createCommand($method, $arguments);
  180. }
  181. public function executeCommand(ICommand $command) {
  182. return $this->_connection->executeCommand($command);
  183. }
  184. public function executeCommandOnShards(ICommand $command) {
  185. $replies = array();
  186. if (Utils::isCluster($this->_connection)) {
  187. foreach($this->_connection as $connection) {
  188. $replies[] = $connection->executeCommand($command);
  189. }
  190. }
  191. else {
  192. $replies[] = $this->_connection->executeCommand($command);
  193. }
  194. return $replies;
  195. }
  196. private function sharedInitializer($argv, $initializer) {
  197. $argc = count($argv);
  198. if ($argc === 0) {
  199. return $this->$initializer();
  200. }
  201. else if ($argc === 1) {
  202. list($arg0) = $argv;
  203. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  204. }
  205. else if ($argc === 2) {
  206. list($arg0, $arg1) = $argv;
  207. return $this->$initializer($arg0, $arg1);
  208. }
  209. return $this->$initializer($this, $arguments);
  210. }
  211. public function pipeline(/* arguments */) {
  212. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  213. }
  214. private function initPipeline(Array $options = null, $pipelineBlock = null) {
  215. $pipeline = null;
  216. if (isset($options)) {
  217. if (isset($options['safe']) && $options['safe'] == true) {
  218. $connection = $this->getConnection();
  219. $pipeline = new CommandPipeline($this, $connection instanceof Connection
  220. ? new Pipeline\SafeExecutor($connection)
  221. : new Pipeline\SafeClusterExecutor($connection)
  222. );
  223. }
  224. else {
  225. $pipeline = new CommandPipeline($this);
  226. }
  227. }
  228. else {
  229. $pipeline = new CommandPipeline($this);
  230. }
  231. return $this->pipelineExecute($pipeline, $pipelineBlock);
  232. }
  233. private function pipelineExecute(CommandPipeline $pipeline, $block) {
  234. return $block !== null ? $pipeline->execute($block) : $pipeline;
  235. }
  236. public function multiExec(/* arguments */) {
  237. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  238. }
  239. private function initMultiExec(Array $options = null, $transBlock = null) {
  240. $multi = isset($options) ? new MultiExecBlock($this, $options) : new MultiExecBlock($this);
  241. return $transBlock !== null ? $multi->execute($transBlock) : $multi;
  242. }
  243. public function pubSubContext() {
  244. return new PubSubContext($this);
  245. }
  246. }
  247. /* ------------------------------------------------------------------------- */
  248. interface IClientOptionsHandler {
  249. public function validate($option, $value);
  250. public function getDefault();
  251. }
  252. class ClientOptionsProfile implements IClientOptionsHandler {
  253. public function validate($option, $value) {
  254. if ($value instanceof RedisServerProfile) {
  255. return $value;
  256. }
  257. if (is_string($value)) {
  258. return RedisServerProfile::get($value);
  259. }
  260. throw new \InvalidArgumentException("Invalid value for option $option");
  261. }
  262. public function getDefault() {
  263. return RedisServerProfile::getDefault();
  264. }
  265. }
  266. class ClientOptionsKeyDistribution implements IClientOptionsHandler {
  267. public function validate($option, $value) {
  268. if ($value instanceof IDistributionStrategy) {
  269. return $value;
  270. }
  271. if (is_string($value)) {
  272. $valueReflection = new \ReflectionClass($value);
  273. if ($valueReflection->isSubclassOf('\Predis\Distribution\IDistributionStrategy')) {
  274. return new $value;
  275. }
  276. }
  277. throw new \InvalidArgumentException("Invalid value for option $option");
  278. }
  279. public function getDefault() {
  280. return new Distribution\HashRing();
  281. }
  282. }
  283. class ClientOptionsIterableMultiBulk implements IClientOptionsHandler {
  284. public function validate($option, $value) {
  285. return (bool) $value;
  286. }
  287. public function getDefault() {
  288. return false;
  289. }
  290. }
  291. class ClientOptionsThrowOnError implements IClientOptionsHandler {
  292. public function validate($option, $value) {
  293. return (bool) $value;
  294. }
  295. public function getDefault() {
  296. return true;
  297. }
  298. }
  299. class ClientOptions {
  300. private static $_optionsHandlers;
  301. private $_options;
  302. public function __construct($options = null) {
  303. self::initializeOptionsHandlers();
  304. $this->initializeOptions($options ?: array());
  305. }
  306. private static function initializeOptionsHandlers() {
  307. if (!isset(self::$_optionsHandlers)) {
  308. self::$_optionsHandlers = self::getOptionsHandlers();
  309. }
  310. }
  311. private static function getOptionsHandlers() {
  312. return array(
  313. 'profile' => new ClientOptionsProfile(),
  314. 'key_distribution' => new ClientOptionsKeyDistribution(),
  315. 'iterable_multibulk' => new ClientOptionsIterableMultiBulk(),
  316. 'throw_on_error' => new ClientOptionsThrowOnError(),
  317. );
  318. }
  319. private function initializeOptions($options) {
  320. foreach ($options as $option => $value) {
  321. if (isset(self::$_optionsHandlers[$option])) {
  322. $handler = self::$_optionsHandlers[$option];
  323. $this->_options[$option] = $handler->validate($option, $value);
  324. }
  325. }
  326. }
  327. public function __get($option) {
  328. if (!isset($this->_options[$option])) {
  329. $defaultValue = self::$_optionsHandlers[$option]->getDefault();
  330. $this->_options[$option] = $defaultValue;
  331. }
  332. return $this->_options[$option];
  333. }
  334. public function __isset($option) {
  335. return isset(self::$_optionsHandlers[$option]);
  336. }
  337. }
  338. /* ------------------------------------------------------------------------- */
  339. class Protocol {
  340. const NEWLINE = "\r\n";
  341. const OK = 'OK';
  342. const ERROR = 'ERR';
  343. const QUEUED = 'QUEUED';
  344. const NULL = 'nil';
  345. const PREFIX_STATUS = '+';
  346. const PREFIX_ERROR = '-';
  347. const PREFIX_INTEGER = ':';
  348. const PREFIX_BULK = '$';
  349. const PREFIX_MULTI_BULK = '*';
  350. }
  351. interface ICommand {
  352. public function getCommandId();
  353. public function canBeHashed();
  354. public function closesConnection();
  355. public function getHash(IDistributionStrategy $distributor);
  356. public function setArgumentsArray(Array $arguments);
  357. public function getArguments();
  358. public function parseResponse($data);
  359. public function serialize();
  360. }
  361. abstract class Command implements ICommand {
  362. private $_arguments, $_hash;
  363. protected function serializeRequest($command, $arguments) {
  364. $newline = Protocol::NEWLINE;
  365. $cmdlen = strlen($command);
  366. $reqlen = count($arguments) + 1;
  367. $buffer = "*{$reqlen}{$newline}\${$cmdlen}{$newline}{$command}{$newline}";
  368. foreach ($arguments as $argument) {
  369. $arglen = strlen($argument);
  370. $buffer .= "\${$arglen}{$newline}{$argument}{$newline}";
  371. }
  372. return $buffer;
  373. }
  374. public function canBeHashed() {
  375. return true;
  376. }
  377. public function getHash(IDistributionStrategy $distributor) {
  378. if (isset($this->_hash)) {
  379. return $this->_hash;
  380. }
  381. else {
  382. if (isset($this->_arguments[0])) {
  383. // TODO: should we throw an exception if the command does
  384. // not support sharding?
  385. $key = $this->_arguments[0];
  386. $start = strpos($key, '{');
  387. $end = strpos($key, '}');
  388. if ($start !== false && $end !== false) {
  389. $key = substr($key, ++$start, $end - $start);
  390. }
  391. $this->_hash = $distributor->generateKey($key);
  392. return $this->_hash;
  393. }
  394. }
  395. return null;
  396. }
  397. public function closesConnection() {
  398. return false;
  399. }
  400. protected function filterArguments(Array $arguments) {
  401. return $arguments;
  402. }
  403. public function setArguments(/* arguments */) {
  404. $this->_arguments = $this->filterArguments(func_get_args());
  405. unset($this->_hash);
  406. }
  407. public function setArgumentsArray(Array $arguments) {
  408. $this->_arguments = $this->filterArguments($arguments);
  409. unset($this->_hash);
  410. }
  411. public function getArguments() {
  412. return isset($this->_arguments) ? $this->_arguments : array();
  413. }
  414. public function getArgument($index = 0) {
  415. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  416. }
  417. public function parseResponse($data) {
  418. return $data;
  419. }
  420. public final function serialize() {
  421. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  422. }
  423. }
  424. /* ------------------------------------------------------------------------- */
  425. interface IResponseHandler {
  426. function handle(IConnectionSingle $connection, $payload);
  427. }
  428. class ResponseStatusHandler implements IResponseHandler {
  429. public function handle(IConnectionSingle $connection, $status) {
  430. if ($status === Protocol::OK) {
  431. return true;
  432. }
  433. else if ($status === Protocol::QUEUED) {
  434. return new ResponseQueued();
  435. }
  436. return $status;
  437. }
  438. }
  439. class ResponseErrorHandler implements IResponseHandler {
  440. public function handle(IConnectionSingle $connection, $errorMessage) {
  441. throw new ServerException(substr($errorMessage, 4));
  442. }
  443. }
  444. class ResponseErrorSilentHandler implements IResponseHandler {
  445. public function handle(IConnectionSingle $connection, $errorMessage) {
  446. return new ResponseError(substr($errorMessage, 4));
  447. }
  448. }
  449. class ResponseBulkHandler implements IResponseHandler {
  450. public function handle(IConnectionSingle $connection, $dataLength) {
  451. if (!is_numeric($dataLength)) {
  452. Utils::onCommunicationException(new MalformedServerResponse(
  453. $connection, "Cannot parse '$dataLength' as data length"
  454. ));
  455. }
  456. if ($dataLength > 0) {
  457. $value = $connection->readBytes($dataLength);
  458. self::discardNewLine($connection);
  459. return $value;
  460. }
  461. else if ($dataLength == 0) {
  462. self::discardNewLine($connection);
  463. return '';
  464. }
  465. return null;
  466. }
  467. private static function discardNewLine(IConnectionSingle $connection) {
  468. if ($connection->readBytes(2) !== Protocol::NEWLINE) {
  469. Utils::onCommunicationException(new MalformedServerResponse(
  470. $connection, 'Did not receive a new-line at the end of a bulk response'
  471. ));
  472. }
  473. }
  474. }
  475. class ResponseMultiBulkHandler implements IResponseHandler {
  476. public function handle(IConnectionSingle $connection, $rawLength) {
  477. if (!is_numeric($rawLength)) {
  478. Utils::onCommunicationException(new MalformedServerResponse(
  479. $connection, "Cannot parse '$rawLength' as data length"
  480. ));
  481. }
  482. $listLength = (int) $rawLength;
  483. if ($listLength === -1) {
  484. return null;
  485. }
  486. $list = array();
  487. if ($listLength > 0) {
  488. $reader = $connection->getResponseReader();
  489. for ($i = 0; $i < $listLength; $i++) {
  490. $list[] = $reader->read($connection);
  491. }
  492. }
  493. return $list;
  494. }
  495. }
  496. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  497. public function handle(IConnectionSingle $connection, $rawLength) {
  498. if (!is_numeric($rawLength)) {
  499. Utils::onCommunicationException(new MalformedServerResponse(
  500. $connection, "Cannot parse '$rawLength' as data length"
  501. ));
  502. }
  503. return new Shared\MultiBulkResponseIterator($connection, (int)$rawLength);
  504. }
  505. }
  506. class ResponseIntegerHandler implements IResponseHandler {
  507. public function handle(IConnectionSingle $connection, $number) {
  508. if (is_numeric($number)) {
  509. return (int) $number;
  510. }
  511. else {
  512. if ($number !== Protocol::NULL) {
  513. Utils::onCommunicationException(new MalformedServerResponse(
  514. $connection, "Cannot parse '$number' as numeric response"
  515. ));
  516. }
  517. return null;
  518. }
  519. }
  520. }
  521. class ResponseReader {
  522. private $_prefixHandlers;
  523. public function __construct() {
  524. $this->initializePrefixHandlers();
  525. }
  526. private function initializePrefixHandlers() {
  527. $this->_prefixHandlers = array(
  528. Protocol::PREFIX_STATUS => new ResponseStatusHandler(),
  529. Protocol::PREFIX_ERROR => new ResponseErrorHandler(),
  530. Protocol::PREFIX_INTEGER => new ResponseIntegerHandler(),
  531. Protocol::PREFIX_BULK => new ResponseBulkHandler(),
  532. Protocol::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  533. );
  534. }
  535. public function setHandler($prefix, IResponseHandler $handler) {
  536. $this->_prefixHandlers[$prefix] = $handler;
  537. }
  538. public function getHandler($prefix) {
  539. if (isset($this->_prefixHandlers[$prefix])) {
  540. return $this->_prefixHandlers[$prefix];
  541. }
  542. }
  543. public function read(IConnectionSingle $connection) {
  544. $header = $connection->readLine();
  545. if ($header === '') {
  546. Utils::onCommunicationException(new MalformedServerResponse(
  547. $connection, 'Unexpected empty header'
  548. ));
  549. }
  550. $prefix = $header[0];
  551. $payload = strlen($header) > 1 ? substr($header, 1) : '';
  552. if (!isset($this->_prefixHandlers[$prefix])) {
  553. Utils::onCommunicationException(new MalformedServerResponse(
  554. $connection, "Unknown prefix '$prefix'"
  555. ));
  556. }
  557. $handler = $this->_prefixHandlers[$prefix];
  558. return $handler->handle($connection, $payload);
  559. }
  560. }
  561. class ResponseError {
  562. private $_message;
  563. public function __construct($message) {
  564. $this->_message = $message;
  565. }
  566. public function __get($property) {
  567. if ($property == 'error') {
  568. return true;
  569. }
  570. if ($property == 'message') {
  571. return $this->_message;
  572. }
  573. }
  574. public function __isset($property) {
  575. return $property === 'error';
  576. }
  577. public function __toString() {
  578. return $this->_message;
  579. }
  580. }
  581. class ResponseQueued {
  582. public $queued = true;
  583. public function __toString() {
  584. return Protocol::QUEUED;
  585. }
  586. }
  587. /* ------------------------------------------------------------------------- */
  588. use Predis\Pipeline\IPipelineExecutor;
  589. class CommandPipeline {
  590. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running, $_executor;
  591. public function __construct(Client $redisClient, IPipelineExecutor $executor = null) {
  592. $this->_redisClient = $redisClient;
  593. $this->_executor = $executor ?: new Pipeline\StandardExecutor();
  594. $this->_pipelineBuffer = array();
  595. $this->_returnValues = array();
  596. }
  597. public function __call($method, $arguments) {
  598. $command = $this->_redisClient->createCommand($method, $arguments);
  599. $this->recordCommand($command);
  600. return $this;
  601. }
  602. private function recordCommand(ICommand $command) {
  603. $this->_pipelineBuffer[] = $command;
  604. }
  605. public function flushPipeline() {
  606. if (count($this->_pipelineBuffer) > 0) {
  607. $connection = $this->_redisClient->getConnection();
  608. $this->_returnValues = array_merge(
  609. $this->_returnValues,
  610. $this->_executor->execute($connection, $this->_pipelineBuffer)
  611. );
  612. $this->_pipelineBuffer = array();
  613. }
  614. return $this;
  615. }
  616. private function setRunning($bool) {
  617. if ($bool == true && $this->_running == true) {
  618. throw new ClientException("This pipeline is already opened");
  619. }
  620. $this->_running = $bool;
  621. }
  622. public function execute($block = null) {
  623. if ($block && !is_callable($block)) {
  624. throw new \InvalidArgumentException('Argument passed must be a callable object');
  625. }
  626. // TODO: do not reuse previously executed pipelines
  627. $this->setRunning(true);
  628. $pipelineBlockException = null;
  629. try {
  630. if ($block !== null) {
  631. $block($this);
  632. }
  633. $this->flushPipeline();
  634. }
  635. catch (\Exception $exception) {
  636. $pipelineBlockException = $exception;
  637. }
  638. $this->setRunning(false);
  639. if ($pipelineBlockException !== null) {
  640. throw $pipelineBlockException;
  641. }
  642. return $this->_returnValues;
  643. }
  644. }
  645. class MultiExecBlock {
  646. private $_initialized, $_discarded, $_insideBlock, $_checkAndSet;
  647. private $_redisClient, $_options, $_commands;
  648. private $_supportsWatch;
  649. public function __construct(Client $redisClient, Array $options = null) {
  650. $this->checkCapabilities($redisClient);
  651. $this->_options = $options ?: array();
  652. $this->_redisClient = $redisClient;
  653. $this->reset();
  654. }
  655. private function checkCapabilities(Client $redisClient) {
  656. if (Utils::isCluster($redisClient->getConnection())) {
  657. throw new ClientException(
  658. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  659. );
  660. }
  661. $profile = $redisClient->getProfile();
  662. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  663. throw new ClientException(
  664. 'The current profile does not support MULTI, EXEC and DISCARD commands'
  665. );
  666. }
  667. $this->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  668. }
  669. private function isWatchSupported() {
  670. if ($this->_supportsWatch === false) {
  671. throw new ClientException(
  672. 'The current profile does not support WATCH and UNWATCH commands'
  673. );
  674. }
  675. }
  676. private function reset() {
  677. $this->_initialized = false;
  678. $this->_discarded = false;
  679. $this->_checkAndSet = false;
  680. $this->_insideBlock = false;
  681. $this->_commands = array();
  682. }
  683. private function initialize() {
  684. if ($this->_initialized === true) {
  685. return;
  686. }
  687. $options = &$this->_options;
  688. $this->_checkAndSet = isset($options['cas']) && $options['cas'];
  689. if (isset($options['watch'])) {
  690. $this->watch($options['watch']);
  691. }
  692. if (!$this->_checkAndSet || ($this->_discarded && $this->_checkAndSet)) {
  693. $this->_redisClient->multi();
  694. if ($this->_discarded) {
  695. $this->_checkAndSet = false;
  696. }
  697. }
  698. $this->_initialized = true;
  699. $this->_discarded = false;
  700. }
  701. public function __call($method, $arguments) {
  702. $this->initialize();
  703. $client = $this->_redisClient;
  704. if ($this->_checkAndSet) {
  705. return call_user_func_array(array($client, $method), $arguments);
  706. }
  707. $command = $client->createCommand($method, $arguments);
  708. $response = $client->executeCommand($command);
  709. if (!isset($response->queued)) {
  710. $this->malformedServerResponse(
  711. 'The server did not respond with a QUEUED status reply'
  712. );
  713. }
  714. $this->_commands[] = $command;
  715. return $this;
  716. }
  717. public function watch($keys) {
  718. $this->isWatchSupported();
  719. if ($this->_initialized && !$this->_checkAndSet) {
  720. throw new ClientException('WATCH inside MULTI is not allowed');
  721. }
  722. return $this->_redisClient->watch($keys);
  723. }
  724. public function multi() {
  725. if ($this->_initialized && $this->_checkAndSet) {
  726. $this->_checkAndSet = false;
  727. $this->_redisClient->multi();
  728. return $this;
  729. }
  730. $this->initialize();
  731. return $this;
  732. }
  733. public function unwatch() {
  734. $this->isWatchSupported();
  735. $this->_redisClient->unwatch();
  736. return $this;
  737. }
  738. public function discard() {
  739. $this->_redisClient->discard();
  740. $this->reset();
  741. $this->_discarded = true;
  742. return $this;
  743. }
  744. public function exec() {
  745. return $this->execute();
  746. }
  747. private function checkBeforeExecution($block) {
  748. if ($this->_insideBlock === true) {
  749. throw new ClientException(
  750. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  751. );
  752. }
  753. if ($block) {
  754. if (!is_callable($block)) {
  755. throw new \InvalidArgumentException(
  756. 'Argument passed must be a callable object'
  757. );
  758. }
  759. if (count($this->_commands) > 0) {
  760. throw new ClientException(
  761. 'Cannot execute a transaction block after using fluent interface'
  762. );
  763. }
  764. }
  765. if (isset($this->_options['retry']) && !isset($block)) {
  766. $this->discard();
  767. throw new \InvalidArgumentException(
  768. 'Automatic retries can be used only when a transaction block is provided'
  769. );
  770. }
  771. }
  772. public function execute($block = null) {
  773. $this->checkBeforeExecution($block);
  774. $reply = null;
  775. $returnValues = array();
  776. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  777. do {
  778. $blockException = null;
  779. if ($block !== null) {
  780. $this->_insideBlock = true;
  781. try {
  782. $block($this);
  783. }
  784. catch (CommunicationException $exception) {
  785. $blockException = $exception;
  786. }
  787. catch (ServerException $exception) {
  788. $blockException = $exception;
  789. }
  790. catch (\Exception $exception) {
  791. $blockException = $exception;
  792. if ($this->_initialized === true) {
  793. $this->discard();
  794. }
  795. }
  796. $this->_insideBlock = false;
  797. if ($blockException !== null) {
  798. throw $blockException;
  799. }
  800. }
  801. if ($this->_initialized === false || count($this->_commands) == 0) {
  802. return;
  803. }
  804. $reply = $this->_redisClient->exec();
  805. if ($reply === null) {
  806. if ($attemptsLeft === 0) {
  807. throw new AbortedMultiExec(
  808. 'The current transaction has been aborted by the server'
  809. );
  810. }
  811. $this->reset();
  812. continue;
  813. }
  814. break;
  815. } while ($attemptsLeft-- > 0);
  816. $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  817. $sizeofReplies = count($execReply);
  818. $commands = &$this->_commands;
  819. if ($sizeofReplies !== count($commands)) {
  820. $this->malformedServerResponse(
  821. 'Unexpected number of responses for a MultiExecBlock'
  822. );
  823. }
  824. for ($i = 0; $i < $sizeofReplies; $i++) {
  825. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  826. ? iterator_to_array($execReply[$i])
  827. : $execReply[$i]
  828. );
  829. unset($commands[$i]);
  830. }
  831. return $returnValues;
  832. }
  833. private function malformedServerResponse($message) {
  834. // Since a MULTI/EXEC block cannot be initialized over a clustered
  835. // connection, we can safely assume that Predis\Client::getConnection()
  836. // will always return an instance of Predis\Connection.
  837. Utils::onCommunicationException(new MalformedServerResponse(
  838. $this->_redisClient->getConnection(), $message
  839. ));
  840. }
  841. }
  842. class PubSubContext implements \Iterator {
  843. const SUBSCRIBE = 'subscribe';
  844. const UNSUBSCRIBE = 'unsubscribe';
  845. const PSUBSCRIBE = 'psubscribe';
  846. const PUNSUBSCRIBE = 'punsubscribe';
  847. const MESSAGE = 'message';
  848. const PMESSAGE = 'pmessage';
  849. const STATUS_VALID = 0x0001;
  850. const STATUS_SUBSCRIBED = 0x0010;
  851. const STATUS_PSUBSCRIBED = 0x0100;
  852. private $_redisClient, $_subscriptions, $_isStillValid, $_position;
  853. public function __construct(Client $redisClient) {
  854. $this->checkCapabilities($redisClient);
  855. $this->_redisClient = $redisClient;
  856. $this->_statusFlags = self::STATUS_VALID;
  857. }
  858. public function __destruct() {
  859. $this->closeContext();
  860. }
  861. private function checkCapabilities(Client $redisClient) {
  862. if (Utils::isCluster($redisClient->getConnection())) {
  863. throw new ClientException(
  864. 'Cannot initialize a PUB/SUB context over a cluster of connections'
  865. );
  866. }
  867. $profile = $redisClient->getProfile();
  868. $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
  869. if ($profile->supportsCommands($commands) === false) {
  870. throw new ClientException(
  871. 'The current profile does not support PUB/SUB related commands'
  872. );
  873. }
  874. }
  875. private function isFlagSet($value) {
  876. return ($this->_statusFlags & $value) === $value;
  877. }
  878. public function subscribe(/* arguments */) {
  879. $this->writeCommand(self::SUBSCRIBE, func_get_args());
  880. $this->_statusFlags |= self::STATUS_SUBSCRIBED;
  881. }
  882. public function unsubscribe(/* arguments */) {
  883. $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
  884. }
  885. public function psubscribe(/* arguments */) {
  886. $this->writeCommand(self::PSUBSCRIBE, func_get_args());
  887. $this->_statusFlags |= self::STATUS_PSUBSCRIBED;
  888. }
  889. public function punsubscribe(/* arguments */) {
  890. $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
  891. }
  892. public function closeContext() {
  893. if ($this->valid()) {
  894. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  895. $this->unsubscribe();
  896. }
  897. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  898. $this->punsubscribe();
  899. }
  900. }
  901. }
  902. private function writeCommand($method, $arguments) {
  903. if (count($arguments) === 1 && is_array($arguments[0])) {
  904. $arguments = $arguments[0];
  905. }
  906. $command = $this->_redisClient->createCommand($method, $arguments);
  907. $this->_redisClient->getConnection()->writeCommand($command);
  908. }
  909. public function rewind() {
  910. // NOOP
  911. }
  912. public function current() {
  913. return $this->getValue();
  914. }
  915. public function key() {
  916. return $this->_position;
  917. }
  918. public function next() {
  919. if ($this->isFlagSet(self::STATUS_VALID)) {
  920. $this->_position++;
  921. }
  922. return $this->_position;
  923. }
  924. public function valid() {
  925. $subscriptions = self::STATUS_SUBSCRIBED + self::STATUS_PSUBSCRIBED;
  926. return $this->isFlagSet(self::STATUS_VALID)
  927. && ($this->_statusFlags & $subscriptions) > 0;
  928. }
  929. private function invalidate() {
  930. $this->_statusFlags = 0x0000;
  931. }
  932. private function getValue() {
  933. $reader = $this->_redisClient->getResponseReader();
  934. $connection = $this->_redisClient->getConnection();
  935. $response = $reader->read($connection);
  936. switch ($response[0]) {
  937. case self::SUBSCRIBE:
  938. case self::UNSUBSCRIBE:
  939. case self::PSUBSCRIBE:
  940. case self::PUNSUBSCRIBE:
  941. if ($response[2] === 0) {
  942. $this->invalidate();
  943. }
  944. case self::MESSAGE:
  945. return (object) array(
  946. 'kind' => $response[0],
  947. 'channel' => $response[1],
  948. 'payload' => $response[2],
  949. );
  950. case self::PMESSAGE:
  951. return (object) array(
  952. 'kind' => $response[0],
  953. 'pattern' => $response[1],
  954. 'channel' => $response[2],
  955. 'payload' => $response[3],
  956. );
  957. default:
  958. throw new ClientException(
  959. "Received an unknown message type {$response[0]} inside of a pubsub context"
  960. );
  961. }
  962. }
  963. }
  964. /* ------------------------------------------------------------------------- */
  965. class ConnectionParameters {
  966. const DEFAULT_SCHEME = 'tcp';
  967. const DEFAULT_HOST = '127.0.0.1';
  968. const DEFAULT_PORT = 6379;
  969. const DEFAULT_TIMEOUT = 5;
  970. private $_parameters;
  971. public function __construct($parameters = null) {
  972. $parameters = $parameters ?: array();
  973. $this->_parameters = is_array($parameters)
  974. ? self::filterConnectionParams($parameters)
  975. : self::parseURI($parameters);
  976. }
  977. private static function paramsExtractor($params, $kv) {
  978. @list($k, $v) = explode('=', $kv);
  979. $params[$k] = $v;
  980. return $params;
  981. }
  982. private static function parseURI($uri) {
  983. if (stripos($uri, 'unix') === 0) {
  984. // hack to support URIs for UNIX sockets with minimal effort
  985. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
  986. }
  987. $parsed = @parse_url($uri);
  988. if ($parsed == false || $parsed['host'] == null) {
  989. throw new ClientException("Invalid URI: $uri");
  990. }
  991. if (array_key_exists('query', $parsed)) {
  992. $query = explode('&', $parsed['query']);
  993. $parsed = array_reduce($query, 'self::paramsExtractor', $parsed);
  994. }
  995. return self::filterConnectionParams($parsed);
  996. }
  997. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  998. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  999. }
  1000. private static function filterConnectionParams($parameters) {
  1001. return array(
  1002. 'scheme' => self::getParamOrDefault($parameters, 'scheme', self::DEFAULT_SCHEME),
  1003. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  1004. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  1005. 'path' => self::getParamOrDefault($parameters, 'path'),
  1006. 'database' => self::getParamOrDefault($parameters, 'database'),
  1007. 'password' => self::getParamOrDefault($parameters, 'password'),
  1008. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  1009. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  1010. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  1011. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  1012. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  1013. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  1014. );
  1015. }
  1016. public function __get($parameter) {
  1017. return $this->_parameters[$parameter];
  1018. }
  1019. public function __isset($parameter) {
  1020. return isset($this->_parameters[$parameter]);
  1021. }
  1022. }
  1023. interface IConnection {
  1024. public function connect();
  1025. public function disconnect();
  1026. public function isConnected();
  1027. public function writeCommand(ICommand $command);
  1028. public function readResponse(ICommand $command);
  1029. public function executeCommand(ICommand $command);
  1030. }
  1031. interface IConnectionSingle extends IConnection {
  1032. public function writeBytes($buffer);
  1033. public function readBytes($length);
  1034. public function readLine();
  1035. public function getParameters();
  1036. public function pushInitCommand(ICommand $command);
  1037. public function __toString();
  1038. }
  1039. interface IConnectionCluster extends IConnection {
  1040. public function getConnection(ICommand $command);
  1041. public function getConnectionById($connectionId);
  1042. }
  1043. final class ConnectionFactory {
  1044. private static $_registeredSchemes;
  1045. private function __construct() {
  1046. // NOOP
  1047. }
  1048. private static function ensureInitialized() {
  1049. if (!isset(self::$_registeredSchemes)) {
  1050. self::$_registeredSchemes = self::getDefaultSchemes();
  1051. }
  1052. }
  1053. private static function getDefaultSchemes() {
  1054. return array(
  1055. 'tcp' => '\Predis\TcpConnection',
  1056. 'redis' => '\Predis\TcpConnection', // compatibility with older versions
  1057. 'unix' => '\Predis\UnixDomainSocketConnection',
  1058. );
  1059. }
  1060. public static function registerScheme($scheme, $connectionClass) {
  1061. self::ensureInitialized();
  1062. $connectionReflection = new \ReflectionClass($connectionClass);
  1063. if (!$connectionReflection->isSubclassOf('\Predis\IConnectionSingle')) {
  1064. throw new ClientException(
  1065. "Cannot register '$connectionClass' as it is not a valid connection class"
  1066. );
  1067. }
  1068. self::$_registeredSchemes[$scheme] = $connectionClass;
  1069. }
  1070. public static function create(ConnectionParameters $parameters, ResponseReader $reader) {
  1071. self::ensureInitialized();
  1072. if (!isset(self::$_registeredSchemes[$parameters->scheme])) {
  1073. throw new ClientException("Unknown connection scheme: {$parameters->scheme}");
  1074. }
  1075. $connection = self::$_registeredSchemes[$parameters->scheme];
  1076. return new $connection($parameters, $reader);
  1077. }
  1078. }
  1079. abstract class Connection implements IConnectionSingle {
  1080. protected $_params, $_socket, $_initCmds, $_reader;
  1081. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  1082. $this->_params = $parameters;
  1083. $this->_initCmds = array();
  1084. $this->_reader = $reader ?: new ResponseReader();
  1085. }
  1086. public function __destruct() {
  1087. $this->disconnect();
  1088. }
  1089. public function isConnected() {
  1090. return is_resource($this->_socket);
  1091. }
  1092. protected abstract function createResource();
  1093. public function connect() {
  1094. if ($this->isConnected()) {
  1095. throw new ClientException('Connection already estabilished');
  1096. }
  1097. $this->createResource();
  1098. }
  1099. public function disconnect() {
  1100. if ($this->isConnected()) {
  1101. fclose($this->_socket);
  1102. }
  1103. }
  1104. public function pushInitCommand(ICommand $command){
  1105. $this->_initCmds[] = $command;
  1106. }
  1107. public function executeCommand(ICommand $command) {
  1108. $this->writeCommand($command);
  1109. if ($command->closesConnection()) {
  1110. return $this->disconnect();
  1111. }
  1112. return $this->readResponse($command);
  1113. }
  1114. protected function onCommunicationException($message, $code = null) {
  1115. Utils::onCommunicationException(
  1116. new CommunicationException($this, $message, $code)
  1117. );
  1118. }
  1119. public function getSocket() {
  1120. if (!$this->isConnected()) {
  1121. $this->connect();
  1122. }
  1123. return $this->_socket;
  1124. }
  1125. public function getResponseReader() {
  1126. return $this->_reader;
  1127. }
  1128. public function getParameters() {
  1129. return $this->_params;
  1130. }
  1131. public function __toString() {
  1132. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  1133. }
  1134. }
  1135. class TcpConnection extends Connection implements IConnectionSingle {
  1136. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  1137. parent::__construct($this->checkParameters($parameters), $reader);
  1138. }
  1139. public function __destruct() {
  1140. if (!$this->_params->connection_persistent) {
  1141. $this->disconnect();
  1142. }
  1143. }
  1144. protected function checkParameters(ConnectionParameters $parameters) {
  1145. if ($parameters->scheme != 'tcp' && $parameters->scheme != 'redis') {
  1146. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  1147. }
  1148. return $parameters;
  1149. }
  1150. protected function createResource() {
  1151. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  1152. $connectFlags = STREAM_CLIENT_CONNECT;
  1153. if ($this->_params->connection_async) {
  1154. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  1155. }
  1156. if ($this->_params->connection_persistent) {
  1157. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1158. }
  1159. $this->_socket = @stream_socket_client(
  1160. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1161. );
  1162. if (!$this->_socket) {
  1163. $this->onCommunicationException(trim($errstr), $errno);
  1164. }
  1165. if (isset($this->_params->read_write_timeout)) {
  1166. $timeoutSeconds = floor($this->_params->read_write_timeout);
  1167. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  1168. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  1169. }
  1170. }
  1171. private function sendInitializationCommands() {
  1172. foreach ($this->_initCmds as $command) {
  1173. $this->writeCommand($command);
  1174. }
  1175. foreach ($this->_initCmds as $command) {
  1176. $this->readResponse($command);
  1177. }
  1178. }
  1179. public function connect() {
  1180. parent::connect();
  1181. if (count($this->_initCmds) > 0){
  1182. $this->sendInitializationCommands();
  1183. }
  1184. }
  1185. public function writeCommand(ICommand $command) {
  1186. $this->writeBytes($command->serialize());
  1187. }
  1188. public function readResponse(ICommand $command) {
  1189. $response = $this->_reader->read($this);
  1190. $skipparse = isset($response->queued) || isset($response->error);
  1191. return $skipparse ? $response : $command->parseResponse($response);
  1192. }
  1193. public function rawCommand($rawCommandData, $closesConnection = false) {
  1194. $this->writeBytes($rawCommandData);
  1195. if ($closesConnection) {
  1196. $this->disconnect();
  1197. return;
  1198. }
  1199. return $this->_reader->read($this);
  1200. }
  1201. public function writeBytes($value) {
  1202. $socket = $this->getSocket();
  1203. while (($length = strlen($value)) > 0) {
  1204. $written = fwrite($socket, $value);
  1205. if ($length === $written) {
  1206. return true;
  1207. }
  1208. if ($written === false || $written === 0) {
  1209. $this->onCommunicationException('Error while writing bytes to the server');
  1210. }
  1211. $value = substr($value, $written);
  1212. }
  1213. return true;
  1214. }
  1215. public function readBytes($length) {
  1216. if ($length == 0) {
  1217. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  1218. }
  1219. $socket = $this->getSocket();
  1220. $value = '';
  1221. do {
  1222. $chunk = fread($socket, $length);
  1223. if ($chunk === false || $chunk === '') {
  1224. $this->onCommunicationException('Error while reading bytes from the server');
  1225. }
  1226. $value .= $chunk;
  1227. }
  1228. while (($length -= strlen($chunk)) > 0);
  1229. return $value;
  1230. }
  1231. public function readLine() {
  1232. $socket = $this->getSocket();
  1233. $value = '';
  1234. do {
  1235. $chunk = fgets($socket);
  1236. if ($chunk === false || strlen($chunk) == 0) {
  1237. $this->onCommunicationException('Error while reading line from the server');
  1238. }
  1239. $value .= $chunk;
  1240. }
  1241. while (substr($value, -2) !== Protocol::NEWLINE);
  1242. return substr($value, 0, -2);
  1243. }
  1244. }
  1245. class UnixDomainSocketConnection extends TcpConnection {
  1246. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  1247. parent::__construct($this->checkParameters($parameters), $reader);
  1248. }
  1249. protected function checkParameters(ConnectionParameters $parameters) {
  1250. if ($parameters->scheme != 'unix') {
  1251. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  1252. }
  1253. if (!file_exists($parameters->path)) {
  1254. throw new \InvalidArgumentException("Could not find {$parameters->path}");
  1255. }
  1256. return $parameters;
  1257. }
  1258. protected function createResource() {
  1259. $uri = sprintf('unix:///%s', $this->_params->path);
  1260. $connectFlags = STREAM_CLIENT_CONNECT;
  1261. if ($this->_params->connection_persistent) {
  1262. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1263. }
  1264. $this->_socket = @stream_socket_client(
  1265. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1266. );
  1267. if (!$this->_socket) {
  1268. $this->onCommunicationException(trim($errstr), $errno);
  1269. }
  1270. }
  1271. }
  1272. class ConnectionCluster implements IConnectionCluster, \IteratorAggregate {
  1273. private $_pool, $_distributor;
  1274. public function __construct(IDistributionStrategy $distributor = null) {
  1275. $this->_pool = array();
  1276. $this->_distributor = $distributor ?: new Distribution\HashRing();
  1277. }
  1278. public function isConnected() {
  1279. foreach ($this->_pool as $connection) {
  1280. if ($connection->isConnected()) {
  1281. return true;
  1282. }
  1283. }
  1284. return false;
  1285. }
  1286. public function connect() {
  1287. foreach ($this->_pool as $connection) {
  1288. $connection->connect();
  1289. }
  1290. }
  1291. public function disconnect() {
  1292. foreach ($this->_pool as $connection) {
  1293. $connection->disconnect();
  1294. }
  1295. }
  1296. public function add(IConnectionSingle $connection) {
  1297. $parameters = $connection->getParameters();
  1298. if (isset($parameters->alias)) {
  1299. $this->_pool[$parameters->alias] = $connection;
  1300. }
  1301. else {
  1302. $this->_pool[] = $connection;
  1303. }
  1304. $this->_distributor->add($connection, $parameters->weight);
  1305. }
  1306. public function getConnection(ICommand $command) {
  1307. if ($command->canBeHashed() === false) {
  1308. throw new ClientException(
  1309. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1310. );
  1311. }
  1312. return $this->_distributor->get($command->getHash($this->_distributor));
  1313. }
  1314. public function getConnectionById($id = null) {
  1315. $alias = $id ?: 0;
  1316. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1317. }
  1318. public function getIterator() {
  1319. return new \ArrayIterator($this->_pool);
  1320. }
  1321. public function writeCommand(ICommand $command) {
  1322. $this->getConnection($command)->writeCommand($command);
  1323. }
  1324. public function readResponse(ICommand $command) {
  1325. return $this->getConnection($command)->readResponse($command);
  1326. }
  1327. public function executeCommand(ICommand $command) {
  1328. $connection = $this->getConnection($command);
  1329. $connection->writeCommand($command);
  1330. return $connection->readResponse($command);
  1331. }
  1332. }
  1333. /* ------------------------------------------------------------------------- */
  1334. abstract class RedisServerProfile {
  1335. private static $_serverProfiles;
  1336. private $_registeredCommands;
  1337. public function __construct() {
  1338. $this->_registeredCommands = $this->getSupportedCommands();
  1339. }
  1340. public abstract function getVersion();
  1341. protected abstract function getSupportedCommands();
  1342. public static function getDefault() {
  1343. return self::get('default');
  1344. }
  1345. public static function getDevelopment() {
  1346. return self::get('dev');
  1347. }
  1348. private static function predisServerProfiles() {
  1349. return array(
  1350. '1.2' => '\Predis\RedisServer_v1_2',
  1351. '2.0' => '\Predis\RedisServer_v2_0',
  1352. 'default' => '\Predis\RedisServer_v2_0',
  1353. 'dev' => '\Predis\RedisServer_vNext',
  1354. );
  1355. }
  1356. public static function registerProfile($profileClass, $aliases) {
  1357. if (!isset(self::$_serverProfiles)) {
  1358. self::$_serverProfiles = self::predisServerProfiles();
  1359. }
  1360. $profileReflection = new \ReflectionClass($profileClass);
  1361. if (!$profileReflection->isSubclassOf('\Predis\RedisServerProfile')) {
  1362. throw new ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1363. }
  1364. if (is_array($aliases)) {
  1365. foreach ($aliases as $alias) {
  1366. self::$_serverProfiles[$alias] = $profileClass;
  1367. }
  1368. }
  1369. else {
  1370. self::$_serverProfiles[$aliases] = $profileClass;
  1371. }
  1372. }
  1373. public static function get($version) {
  1374. if (!isset(self::$_serverProfiles)) {
  1375. self::$_serverProfiles = self::predisServerProfiles();
  1376. }
  1377. if (!isset(self::$_serverProfiles[$version])) {
  1378. throw new ClientException("Unknown server profile: $version");
  1379. }
  1380. $profile = self::$_serverProfiles[$version];
  1381. return new $profile();
  1382. }
  1383. public function supportsCommands(Array $commands) {
  1384. foreach ($commands as $command) {
  1385. if ($this->supportsCommand($command) === false) {
  1386. return false;
  1387. }
  1388. }
  1389. return true;
  1390. }
  1391. public function supportsCommand($command) {
  1392. return isset($this->_registeredCommands[$command]);
  1393. }
  1394. public function createCommand($method, $arguments = array()) {
  1395. if (!isset($this->_registeredCommands[$method])) {
  1396. throw new ClientException("'$method' is not a registered Redis command");
  1397. }
  1398. $commandClass = $this->_registeredCommands[$method];
  1399. $command = new $commandClass();
  1400. $command->setArgumentsArray($arguments);
  1401. return $command;
  1402. }
  1403. public function registerCommands(Array $commands) {
  1404. foreach ($commands as $command => $aliases) {
  1405. $this->registerCommand($command, $aliases);
  1406. }
  1407. }
  1408. public function registerCommand($command, $aliases) {
  1409. $commandReflection = new \ReflectionClass($command);
  1410. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  1411. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1412. }
  1413. if (is_array($aliases)) {
  1414. foreach ($aliases as $alias) {
  1415. $this->_registeredCommands[$alias] = $command;
  1416. }
  1417. }
  1418. else {
  1419. $this->_registeredCommands[$aliases] = $command;
  1420. }
  1421. }
  1422. public function __toString() {
  1423. return $this->getVersion();
  1424. }
  1425. }
  1426. class RedisServer_v1_2 extends RedisServerProfile {
  1427. public function getVersion() { return '1.2'; }
  1428. public function getSupportedCommands() {
  1429. return array(
  1430. /* miscellaneous commands */
  1431. 'ping' => '\Predis\Commands\Ping',
  1432. 'echo' => '\Predis\Commands\DoEcho',
  1433. 'auth' => '\Predis\Commands\Auth',
  1434. /* connection handling */
  1435. 'quit' => '\Predis\Commands\Quit',
  1436. /* commands operating on string values */
  1437. 'set' => '\Predis\Commands\Set',
  1438. 'setnx' => '\Predis\Commands\SetPreserve',
  1439. 'mset' => '\Predis\Commands\SetMultiple',
  1440. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1441. 'get' => '\Predis\Commands\Get',
  1442. 'mget' => '\Predis\Commands\GetMultiple',
  1443. 'getset' => '\Predis\Commands\GetSet',
  1444. 'incr' => '\Predis\Commands\Increment',
  1445. 'incrby' => '\Predis\Commands\IncrementBy',
  1446. 'decr' => '\Predis\Commands\Decrement',
  1447. 'decrby' => '\Predis\Commands\DecrementBy',
  1448. 'exists' => '\Predis\Commands\Exists',
  1449. 'del' => '\Predis\Commands\Delete',
  1450. 'type' => '\Predis\Commands\Type',
  1451. /* commands operating on the key space */
  1452. 'keys' => '\Predis\Commands\Keys',
  1453. 'randomkey' => '\Predis\Commands\RandomKey',
  1454. 'rename' => '\Predis\Commands\Rename',
  1455. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1456. 'expire' => '\Predis\Commands\Expire',
  1457. 'expireat' => '\Predis\Commands\ExpireAt',
  1458. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1459. 'ttl' => '\Predis\Commands\TimeToLive',
  1460. /* commands operating on lists */
  1461. 'rpush' => '\Predis\Commands\ListPushTail',
  1462. 'lpush' => '\Predis\Commands\ListPushHead',
  1463. 'llen' => '\Predis\Commands\ListLength',
  1464. 'lrange' => '\Predis\Commands\ListRange',
  1465. 'ltrim' => '\Predis\Commands\ListTrim',
  1466. 'lindex' => '\Predis\Commands\ListIndex',
  1467. 'lset' => '\Predis\Commands\ListSet',
  1468. 'lrem' => '\Predis\Commands\ListRemove',
  1469. 'lpop' => '\Predis\Commands\ListPopFirst',
  1470. 'rpop' => '\Predis\Commands\ListPopLast',
  1471. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1472. /* commands operating on sets */
  1473. 'sadd' => '\Predis\Commands\SetAdd',
  1474. 'srem' => '\Predis\Commands\SetRemove',
  1475. 'spop' => '\Predis\Commands\SetPop',
  1476. 'smove' => '\Predis\Commands\SetMove',
  1477. 'scard' => '\Predis\Commands\SetCardinality',
  1478. 'sismember' => '\Predis\Commands\SetIsMember',
  1479. 'sinter' => '\Predis\Commands\SetIntersection',
  1480. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1481. 'sunion' => '\Predis\Commands\SetUnion',
  1482. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1483. 'sdiff' => '\Predis\Commands\SetDifference',
  1484. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1485. 'smembers' => '\Predis\Commands\SetMembers',
  1486. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1487. /* commands operating on sorted sets */
  1488. 'zadd' => '\Predis\Commands\ZSetAdd',
  1489. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1490. 'zrem' => '\Predis\Commands\ZSetRemove',
  1491. 'zrange' => '\Predis\Commands\ZSetRange',
  1492. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1493. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1494. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1495. 'zscore' => '\Predis\Commands\ZSetScore',
  1496. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1497. /* multiple databases handling commands */
  1498. 'select' => '\Predis\Commands\SelectDatabase',
  1499. 'move' => '\Predis\Commands\MoveKey',
  1500. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1501. 'flushall' => '\Predis\Commands\FlushAll',
  1502. /* sorting */
  1503. 'sort' => '\Predis\Commands\Sort',
  1504. /* remote server control commands */
  1505. 'info' => '\Predis\Commands\Info',
  1506. 'slaveof' => '\Predis\Commands\SlaveOf',
  1507. /* persistence control commands */
  1508. 'save' => '\Predis\Commands\Save',
  1509. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1510. 'lastsave' => '\Predis\Commands\LastSave',
  1511. 'shutdown' => '\Predis\Commands\Shutdown',
  1512. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1513. );
  1514. }
  1515. }
  1516. class RedisServer_v2_0 extends RedisServer_v1_2 {
  1517. public function getVersion() { return '2.0'; }
  1518. public function getSupportedCommands() {
  1519. return array_merge(parent::getSupportedCommands(), array(
  1520. /* transactions */
  1521. 'multi' => '\Predis\Commands\Multi',
  1522. 'exec' => '\Predis\Commands\Exec',
  1523. 'discard' => '\Predis\Commands\Discard',
  1524. /* commands operating on string values */
  1525. 'setex' => '\Predis\Commands\SetExpire',
  1526. 'append' => '\Predis\Commands\Append',
  1527. 'substr' => '\Predis\Commands\Substr',
  1528. /* commands operating on lists */
  1529. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1530. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1531. /* commands operating on sorted sets */
  1532. 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
  1533. 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
  1534. 'zcount' => '\Predis\Commands\ZSetCount',
  1535. 'zrank' => '\Predis\Commands\ZSetRank',
  1536. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1537. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1538. /* commands operating on hashes */
  1539. 'hset' => '\Predis\Commands\HashSet',
  1540. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1541. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1542. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1543. 'hget' => '\Predis\Commands\HashGet',
  1544. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1545. 'hdel' => '\Predis\Commands\HashDelete',
  1546. 'hexists' => '\Predis\Commands\HashExists',
  1547. 'hlen' => '\Predis\Commands\HashLength',
  1548. 'hkeys' => '\Predis\Commands\HashKeys',
  1549. 'hvals' => '\Predis\Commands\HashValues',
  1550. 'hgetall' => '\Predis\Commands\HashGetAll',
  1551. /* publish - subscribe */
  1552. 'subscribe' => '\Predis\Commands\Subscribe',
  1553. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1554. 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
  1555. 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
  1556. 'publish' => '\Predis\Commands\Publish',
  1557. /* remote server control commands */
  1558. 'config' => '\Predis\Commands\Config',
  1559. ));
  1560. }
  1561. }
  1562. class RedisServer_vNext extends RedisServer_v2_0 {
  1563. public function getVersion() { return '2.1'; }
  1564. public function getSupportedCommands() {
  1565. return array_merge(parent::getSupportedCommands(), array(
  1566. /* transactions */
  1567. 'watch' => '\Predis\Commands\Watch',
  1568. 'unwatch' => '\Predis\Commands\Unwatch',
  1569. /* commands operating on string values */
  1570. 'strlen' => '\Predis\Commands\Strlen',
  1571. 'setrange' => '\Predis\Commands\SetRange',
  1572. 'getrange' => '\Predis\Commands\GetRange',
  1573. 'setbit' => '\Predis\Commands\SetBit',
  1574. 'getbit' => '\Predis\Commands\GetBit',
  1575. /* commands operating on the key space */
  1576. 'persist' => '\Predis\Commands\Persist',
  1577. /* commands operating on lists */
  1578. 'rpushx' => '\Predis\Commands\ListPushTailX',
  1579. 'lpushx' => '\Predis\Commands\ListPushHeadX',
  1580. 'linsert' => '\Predis\Commands\ListInsert',
  1581. 'brpoplpush' => '\Predis\Commands\ListPopLastPushHeadBlocking',
  1582. /* commands operating on sorted sets */
  1583. 'zrevrangebyscore' => '\Predis\Commands\ZSetReverseRangeByScore',
  1584. ));
  1585. }
  1586. }
  1587. /* ------------------------------------------------------------------------- */
  1588. namespace Predis\Pipeline;
  1589. use Predis\IConnection, Predis\ServerException, Predis\CommunicationException;
  1590. interface IPipelineExecutor {
  1591. public function execute(IConnection $connection, &$commands);
  1592. }
  1593. class StandardExecutor implements IPipelineExecutor {
  1594. public function execute(IConnection $connection, &$commands) {
  1595. $sizeofPipe = count($commands);
  1596. $values = array();
  1597. foreach ($commands as $command) {
  1598. $connection->writeCommand($command);
  1599. }
  1600. try {
  1601. for ($i = 0; $i < $sizeofPipe; $i++) {
  1602. $response = $connection->readResponse($commands[$i]);
  1603. $values[] = $response instanceof \Iterator
  1604. ? iterator_to_array($response)
  1605. : $response;
  1606. unset($commands[$i]);
  1607. }
  1608. }
  1609. catch (ServerException $exception) {
  1610. // force disconnection to prevent protocol desynchronization
  1611. $connection->disconnect();
  1612. throw $exception;
  1613. }
  1614. return $values;
  1615. }
  1616. }
  1617. class SafeExecutor implements IPipelineExecutor {
  1618. public function execute(IConnection $connection, &$commands) {
  1619. $sizeofPipe = count($commands);
  1620. $values = array();
  1621. foreach ($commands as $command) {
  1622. try {
  1623. $connection->writeCommand($command);
  1624. }
  1625. catch (CommunicationException $exception) {
  1626. return array_fill(0, $sizeofPipe, $exception);
  1627. }
  1628. }
  1629. for ($i = 0; $i < $sizeofPipe; $i++) {
  1630. $command = $commands[$i];
  1631. unset($commands[$i]);
  1632. try {
  1633. $response = $connection->readResponse($command);
  1634. $values[] = ($response instanceof \Iterator
  1635. ? iterator_to_array($response)
  1636. : $response
  1637. );
  1638. }
  1639. catch (ServerException $exception) {
  1640. $values[] = $exception->toResponseError();
  1641. }
  1642. catch (CommunicationException $exception) {
  1643. $toAdd = count($commands) - count($values);
  1644. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  1645. break;
  1646. }
  1647. }
  1648. return $values;
  1649. }
  1650. }
  1651. class SafeClusterExecutor implements IPipelineExecutor {
  1652. public function execute(IConnection $connection, &$commands) {
  1653. $connectionExceptions = array();
  1654. $sizeofPipe = count($commands);
  1655. $values = array();
  1656. foreach ($commands as $command) {
  1657. $cmdConnection = $connection->getConnection($command);
  1658. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  1659. continue;
  1660. }
  1661. try {
  1662. $cmdConnection->writeCommand($command);
  1663. }
  1664. catch (CommunicationException $exception) {
  1665. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  1666. }
  1667. }
  1668. for ($i = 0; $i < $sizeofPipe; $i++) {
  1669. $command = $commands[$i];
  1670. unset($commands[$i]);
  1671. $cmdConnection = $connection->getConnection($command);
  1672. $connectionObjectHash = spl_object_hash($cmdConnection);
  1673. if (isset($connectionExceptions[$connectionObjectHash])) {
  1674. $values[] = $connectionExceptions[$connectionObjectHash];
  1675. continue;
  1676. }
  1677. try {
  1678. $response = $cmdConnection->readResponse($command);
  1679. $values[] = ($response instanceof \Iterator
  1680. ? iterator_to_array($response)
  1681. : $response
  1682. );
  1683. }
  1684. catch (ServerException $exception) {
  1685. $values[] = $exception->toResponseError();
  1686. }
  1687. catch (CommunicationException $exception) {
  1688. $values[] = $exception;
  1689. $connectionExceptions[$connectionObjectHash] = $exception;
  1690. }
  1691. }
  1692. return $values;
  1693. }
  1694. }
  1695. /* ------------------------------------------------------------------------- */
  1696. namespace Predis\Distribution;
  1697. interface IDistributionStrategy {
  1698. public function add($node, $weight = null);
  1699. public function remove($node);
  1700. public function get($key);
  1701. public function generateKey($value);
  1702. }
  1703. class EmptyRingException extends \Exception { }
  1704. class HashRing implements IDistributionStrategy {
  1705. const DEFAULT_REPLICAS = 128;
  1706. const DEFAULT_WEIGHT = 100;
  1707. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1708. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1709. $this->_replicas = $replicas;
  1710. $this->_nodes = array();
  1711. }
  1712. public function add($node, $weight = null) {
  1713. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1714. // last wins, thus the order in which nodes are added is significant.
  1715. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT);
  1716. $this->reset();
  1717. }
  1718. public function remove($node) {
  1719. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1720. // scratch, in order to reassign possible hashes with collisions to the
  1721. // right node according to the order in which they were added in the
  1722. // first place.
  1723. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1724. if ($this->_nodes[$i]['object'] === $node) {
  1725. array_splice($this->_nodes, $i, 1);
  1726. $this->reset();
  1727. break;
  1728. }
  1729. }
  1730. }
  1731. private function reset() {
  1732. unset($this->_ring);
  1733. unset($this->_ringKeys);
  1734. unset($this->_ringKeysCount);
  1735. }
  1736. private function isInitialized() {
  1737. return isset($this->_ringKeys);
  1738. }
  1739. private function computeTotalWeight() {
  1740. // TODO: array_reduce + lambda for PHP 5.3
  1741. $totalWeight = 0;
  1742. foreach ($this->_nodes as $node) {
  1743. $totalWeight += $node['weight'];
  1744. }
  1745. return $totalWeight;
  1746. }
  1747. private function initialize() {
  1748. if ($this->isInitialized()) {
  1749. return;
  1750. }
  1751. if (count($this->_nodes) === 0) {
  1752. throw new EmptyRingException('Cannot initialize empty hashring');
  1753. }
  1754. $this->_ring = array();
  1755. $totalWeight = $this->computeTotalWeight();
  1756. $nodesCount = count($this->_nodes);
  1757. foreach ($this->_nodes as $node) {
  1758. $weightRatio = $node['weight'] / $totalWeight;
  1759. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1760. }
  1761. ksort($this->_ring, SORT_NUMERIC);
  1762. $this->_ringKeys = array_keys($this->_ring);
  1763. $this->_ringKeysCount = count($this->_ringKeys);
  1764. }
  1765. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1766. $nodeObject = $node['object'];
  1767. $nodeHash = (string) $nodeObject;
  1768. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1769. for ($i = 0; $i < $replicas; $i++) {
  1770. $key = crc32("$nodeHash:$i");
  1771. $ring[$key] = $nodeObject;
  1772. }
  1773. }
  1774. public function generateKey($value) {
  1775. return crc32($value);
  1776. }
  1777. public function get($key) {
  1778. return $this->_ring[$this->getNodeKey($key)];
  1779. }
  1780. private function getNodeKey($key) {
  1781. $this->initialize();
  1782. $ringKeys = $this->_ringKeys;
  1783. $upper = $this->_ringKeysCount - 1;
  1784. $lower = 0;
  1785. while ($lower <= $upper) {
  1786. $index = ($lower + $upper) >> 1;
  1787. $item = $ringKeys[$index];
  1788. if ($item > $key) {
  1789. $upper = $index - 1;
  1790. }
  1791. else if ($item < $key) {
  1792. $lower = $index + 1;
  1793. }
  1794. else {
  1795. return $item;
  1796. }
  1797. }
  1798. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1799. }
  1800. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1801. // NOTE: binary search for the last item in _ringkeys with a value
  1802. // less or equal to the key. If no such item exists, return the
  1803. // last item.
  1804. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1805. }
  1806. }
  1807. class KetamaPureRing extends HashRing {
  1808. const DEFAULT_REPLICAS = 160;
  1809. public function __construct() {
  1810. parent::__construct($this::DEFAULT_REPLICAS);
  1811. }
  1812. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1813. $nodeObject = $node['object'];
  1814. $nodeHash = (string) $nodeObject;
  1815. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1816. for ($i = 0; $i < $replicas; $i++) {
  1817. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1818. foreach ($unpackedDigest as $key) {
  1819. $ring[$key] = $nodeObject;
  1820. }
  1821. }
  1822. }
  1823. public function generateKey($value) {
  1824. $hash = unpack('V', md5($value, true));
  1825. return $hash[1];
  1826. }
  1827. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1828. // NOTE: binary search for the first item in _ringkeys with a value
  1829. // greater or equal to the key. If no such item exists, return the
  1830. // first item.
  1831. return $lower < $ringKeysCount ? $lower : 0;
  1832. }
  1833. }
  1834. /* ------------------------------------------------------------------------- */
  1835. namespace Predis\Shared;
  1836. use Predis\IConnection, Predis\IConnectionSingle, Predis\IConnectionCluster,
  1837. Predis\CommunicationException;
  1838. class Utils {
  1839. public static function isCluster(IConnection $connection) {
  1840. return $connection instanceof IConnectionCluster;
  1841. }
  1842. public static function onCommunicationException(CommunicationException $exception) {
  1843. if ($exception->shouldResetConnection()) {
  1844. $connection = $exception->getConnection();
  1845. if ($connection->isConnected()) {
  1846. $connection->disconnect();
  1847. }
  1848. }
  1849. throw $exception;
  1850. }
  1851. public static function filterArrayArguments(Array $arguments) {
  1852. if (count($arguments) === 1 && is_array($arguments[0])) {
  1853. return $arguments[0];
  1854. }
  1855. return $arguments;
  1856. }
  1857. }
  1858. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1859. protected $_position, $_current, $_replySize;
  1860. public function rewind() {
  1861. // NOOP
  1862. }
  1863. public function current() {
  1864. return $this->_current;
  1865. }
  1866. public function key() {
  1867. return $this->_position;
  1868. }
  1869. public function next() {
  1870. if (++$this->_position < $this->_replySize) {
  1871. $this->_current = $this->getValue();
  1872. }
  1873. return $this->_position;
  1874. }
  1875. public function valid() {
  1876. return $this->_position < $this->_replySize;
  1877. }
  1878. public function count() {
  1879. // NOTE: use count if you want to get the size of the current multi-bulk
  1880. // response without using iterator_count (which actually consumes
  1881. // our iterator to calculate the size, and we cannot perform a rewind)
  1882. return $this->_replySize;
  1883. }
  1884. protected abstract function getValue();
  1885. }
  1886. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1887. private $_connection;
  1888. public function __construct(IConnectionSingle $connection, $size) {
  1889. $this->_connection = $connection;
  1890. $this->_reader = $connection->getResponseReader();
  1891. $this->_position = 0;
  1892. $this->_current = $size > 0 ? $this->getValue() : null;
  1893. $this->_replySize = $size;
  1894. }
  1895. public function __destruct() {
  1896. // when the iterator is garbage-collected (e.g. it goes out of the
  1897. // scope of a foreach) but it has not reached its end, we must sync
  1898. // the client with the queued elements that have not been read from
  1899. // the connection with the server.
  1900. $this->sync();
  1901. }
  1902. public function sync($drop = false) {
  1903. if ($drop == true) {
  1904. if ($this->valid()) {
  1905. $this->_position = $this->_replySize;
  1906. $this->_connection->disconnect();
  1907. }
  1908. }
  1909. else {
  1910. while ($this->valid()) {
  1911. $this->next();
  1912. }
  1913. }
  1914. }
  1915. protected function getValue() {
  1916. return $this->_reader->read($this->_connection);
  1917. }
  1918. }
  1919. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1920. private $_iterator;
  1921. public function __construct(MultiBulkResponseIterator $iterator) {
  1922. $virtualSize = count($iterator) / 2;
  1923. $this->_iterator = $iterator;
  1924. $this->_position = 0;
  1925. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1926. $this->_replySize = $virtualSize;
  1927. }
  1928. public function __destruct() {
  1929. $this->_iterator->sync();
  1930. }
  1931. protected function getValue() {
  1932. $k = $this->_iterator->current();
  1933. $this->_iterator->next();
  1934. $v = $this->_iterator->current();
  1935. $this->_iterator->next();
  1936. return array($k, $v);
  1937. }
  1938. }
  1939. /* ------------------------------------------------------------------------- */
  1940. namespace Predis\Commands;
  1941. use Predis\Command, Predis\Shared\Utils, Predis\Shared\MultiBulkResponseKVIterator;
  1942. /* miscellaneous commands */
  1943. class Ping extends Command {
  1944. public function canBeHashed() { return false; }
  1945. public function getCommandId() { return 'PING'; }
  1946. public function parseResponse($data) {
  1947. return $data === 'PONG' ? true : false;
  1948. }
  1949. }
  1950. class DoEcho extends Command {
  1951. public function canBeHashed() { return false; }
  1952. public function getCommandId() { return 'ECHO'; }
  1953. }
  1954. class Auth extends Command {
  1955. public function canBeHashed() { return false; }
  1956. public function getCommandId() { return 'AUTH'; }
  1957. }
  1958. /* connection handling */
  1959. class Quit extends Command {
  1960. public function canBeHashed() { return false; }
  1961. public function getCommandId() { return 'QUIT'; }
  1962. public function closesConnection() { return true; }
  1963. }
  1964. /* commands operating on string values */
  1965. class Set extends Command {
  1966. public function getCommandId() { return 'SET'; }
  1967. }
  1968. class SetExpire extends Command {
  1969. public function getCommandId() { return 'SETEX'; }
  1970. }
  1971. class SetPreserve extends Command {
  1972. public function getCommandId() { return 'SETNX'; }
  1973. public function parseResponse($data) { return (bool) $data; }
  1974. }
  1975. class SetMultiple extends Command {
  1976. public function canBeHashed() { return false; }
  1977. public function getCommandId() { return 'MSET'; }
  1978. public function filterArguments(Array $arguments) {
  1979. if (count($arguments) === 1 && is_array($arguments[0])) {
  1980. $flattenedKVs = array();
  1981. $args = &$arguments[0];
  1982. foreach ($args as $k => $v) {
  1983. $flattenedKVs[] = $k;
  1984. $flattenedKVs[] = $v;
  1985. }
  1986. return $flattenedKVs;
  1987. }
  1988. return $arguments;
  1989. }
  1990. }
  1991. class SetMultiplePreserve extends SetMultiple {
  1992. public function canBeHashed() { return false; }
  1993. public function getCommandId() { return 'MSETNX'; }
  1994. public function parseResponse($data) { return (bool) $data; }
  1995. }
  1996. class Get extends Command {
  1997. public function getCommandId() { return 'GET'; }
  1998. }
  1999. class GetMultiple extends Command {
  2000. public function canBeHashed() { return false; }
  2001. public function getCommandId() { return 'MGET'; }
  2002. public function filterArguments(Array $arguments) {
  2003. return Utils::filterArrayArguments($arguments);
  2004. }
  2005. }
  2006. class GetSet extends Command {
  2007. public function getCommandId() { return 'GETSET'; }
  2008. }
  2009. class Increment extends Command {
  2010. public function getCommandId() { return 'INCR'; }
  2011. }
  2012. class IncrementBy extends Command {
  2013. public function getCommandId() { return 'INCRBY'; }
  2014. }
  2015. class Decrement extends Command {
  2016. public function getCommandId() { return 'DECR'; }
  2017. }
  2018. class DecrementBy extends Command {
  2019. public function getCommandId() { return 'DECRBY'; }
  2020. }
  2021. class Exists extends Command {
  2022. public function getCommandId() { return 'EXISTS'; }
  2023. public function parseResponse($data) { return (bool) $data; }
  2024. }
  2025. class Delete extends Command {
  2026. public function getCommandId() { return 'DEL'; }
  2027. public function filterArguments(Array $arguments) {
  2028. return Utils::filterArrayArguments($arguments);
  2029. }
  2030. }
  2031. class Type extends Command {
  2032. public function getCommandId() { return 'TYPE'; }
  2033. }
  2034. class Append extends Command {
  2035. public function getCommandId() { return 'APPEND'; }
  2036. }
  2037. class SetRange extends Command {
  2038. public function getCommandId() { return 'SETRANGE'; }
  2039. }
  2040. class GetRange extends Command {
  2041. public function getCommandId() { return 'GETRANGE'; }
  2042. }
  2043. class Substr extends Command {
  2044. public function getCommandId() { return 'SUBSTR'; }
  2045. }
  2046. class SetBit extends Command {
  2047. public function getCommandId() { return 'SETBIT'; }
  2048. }
  2049. class GetBit extends Command {
  2050. public function getCommandId() { return 'GETBIT'; }
  2051. }
  2052. class Strlen extends Command {
  2053. public function getCommandId() { return 'STRLEN'; }
  2054. }
  2055. /* commands operating on the key space */
  2056. class Keys extends Command {
  2057. public function canBeHashed() { return false; }
  2058. public function getCommandId() { return 'KEYS'; }
  2059. public function parseResponse($data) {
  2060. // TODO: is this behaviour correct?
  2061. if (is_array($data) || $data instanceof \Iterator) {
  2062. return $data;
  2063. }
  2064. return strlen($data) > 0 ? explode(' ', $data) : array();
  2065. }
  2066. }
  2067. class RandomKey extends Command {
  2068. public function canBeHashed() { return false; }
  2069. public function getCommandId() { return 'RANDOMKEY'; }
  2070. public function parseResponse($data) { return $data !== '' ? $data : null; }
  2071. }
  2072. class Rename extends Command {
  2073. public function canBeHashed() { return false; }
  2074. public function getCommandId() { return 'RENAME'; }
  2075. }
  2076. class RenamePreserve extends Command {
  2077. public function canBeHashed() { return false; }
  2078. public function getCommandId() { return 'RENAMENX'; }
  2079. public function parseResponse($data) { return (bool) $data; }
  2080. }
  2081. class Expire extends Command {
  2082. public function getCommandId() { return 'EXPIRE'; }
  2083. public function parseResponse($data) { return (bool) $data; }
  2084. }
  2085. class ExpireAt extends Command {
  2086. public function getCommandId() { return 'EXPIREAT'; }
  2087. public function parseResponse($data) { return (bool) $data; }
  2088. }
  2089. class Persist extends Command {
  2090. public function getCommandId() { return 'PERSIST'; }
  2091. public function parseResponse($data) { return (bool) $data; }
  2092. }
  2093. class DatabaseSize extends Command {
  2094. public function canBeHashed() { return false; }
  2095. public function getCommandId() { return 'DBSIZE'; }
  2096. }
  2097. class TimeToLive extends Command {
  2098. public function getCommandId() { return 'TTL'; }
  2099. }
  2100. /* commands operating on lists */
  2101. class ListPushTail extends Command {
  2102. public function getCommandId() { return 'RPUSH'; }
  2103. }
  2104. class ListPushTailX extends Command {
  2105. public function getCommandId() { return 'RPUSHX'; }
  2106. }
  2107. class ListPushHead extends Command {
  2108. public function getCommandId() { return 'LPUSH'; }
  2109. }
  2110. class ListPushHeadX extends Command {
  2111. public function getCommandId() { return 'LPUSHX'; }
  2112. }
  2113. class ListLength extends Command {
  2114. public function getCommandId() { return 'LLEN'; }
  2115. }
  2116. class ListRange extends Command {
  2117. public function getCommandId() { return 'LRANGE'; }
  2118. }
  2119. class ListTrim extends Command {
  2120. public function getCommandId() { return 'LTRIM'; }
  2121. }
  2122. class ListIndex extends Command {
  2123. public function getCommandId() { return 'LINDEX'; }
  2124. }
  2125. class ListSet extends Command {
  2126. public function getCommandId() { return 'LSET'; }
  2127. }
  2128. class ListRemove extends Command {
  2129. public function getCommandId() { return 'LREM'; }
  2130. }
  2131. class ListPopLastPushHead extends Command {
  2132. public function getCommandId() { return 'RPOPLPUSH'; }
  2133. }
  2134. class ListPopLastPushHeadBlocking extends Command {
  2135. public function getCommandId() { return 'BRPOPLPUSH'; }
  2136. }
  2137. class ListPopFirst extends Command {
  2138. public function getCommandId() { return 'LPOP'; }
  2139. }
  2140. class ListPopLast extends Command {
  2141. public function getCommandId() { return 'RPOP'; }
  2142. }
  2143. class ListPopFirstBlocking extends Command {
  2144. public function getCommandId() { return 'BLPOP'; }
  2145. }
  2146. class ListPopLastBlocking extends Command {
  2147. public function getCommandId() { return 'BRPOP'; }
  2148. }
  2149. class ListInsert extends Command {
  2150. public function getCommandId() { return 'LINSERT'; }
  2151. }
  2152. /* commands operating on sets */
  2153. class SetAdd extends Command {
  2154. public function getCommandId() { return 'SADD'; }
  2155. public function parseResponse($data) { return (bool) $data; }
  2156. }
  2157. class SetRemove extends Command {
  2158. public function getCommandId() { return 'SREM'; }
  2159. public function parseResponse($data) { return (bool) $data; }
  2160. }
  2161. class SetPop extends Command {
  2162. public function getCommandId() { return 'SPOP'; }
  2163. }
  2164. class SetMove extends Command {
  2165. public function canBeHashed() { return false; }
  2166. public function getCommandId() { return 'SMOVE'; }
  2167. public function parseResponse($data) { return (bool) $data; }
  2168. }
  2169. class SetCardinality extends Command {
  2170. public function getCommandId() { return 'SCARD'; }
  2171. }
  2172. class SetIsMember extends Command {
  2173. public function getCommandId() { return 'SISMEMBER'; }
  2174. public function parseResponse($data) { return (bool) $data; }
  2175. }
  2176. class SetIntersection extends Command {
  2177. public function getCommandId() { return 'SINTER'; }
  2178. public function filterArguments(Array $arguments) {
  2179. return Utils::filterArrayArguments($arguments);
  2180. }
  2181. }
  2182. class SetIntersectionStore extends Command {
  2183. public function getCommandId() { return 'SINTERSTORE'; }
  2184. public function filterArguments(Array $arguments) {
  2185. return Utils::filterArrayArguments($arguments);
  2186. }
  2187. }
  2188. class SetUnion extends SetIntersection {
  2189. public function getCommandId() { return 'SUNION'; }
  2190. }
  2191. class SetUnionStore extends SetIntersectionStore {
  2192. public function getCommandId() { return 'SUNIONSTORE'; }
  2193. }
  2194. class SetDifference extends SetIntersection {
  2195. public function getCommandId() { return 'SDIFF'; }
  2196. }
  2197. class SetDifferenceStore extends SetIntersectionStore {
  2198. public function getCommandId() { return 'SDIFFSTORE'; }
  2199. }
  2200. class SetMembers extends Command {
  2201. public function getCommandId() { return 'SMEMBERS'; }
  2202. }
  2203. class SetRandomMember extends Command {
  2204. public function getCommandId() { return 'SRANDMEMBER'; }
  2205. }
  2206. /* commands operating on sorted sets */
  2207. class ZSetAdd extends Command {
  2208. public function getCommandId() { return 'ZADD'; }
  2209. public function parseResponse($data) { return (bool) $data; }
  2210. }
  2211. class ZSetIncrementBy extends Command {
  2212. public function getCommandId() { return 'ZINCRBY'; }
  2213. }
  2214. class ZSetRemove extends Command {
  2215. public function getCommandId() { return 'ZREM'; }
  2216. public function parseResponse($data) { return (bool) $data; }
  2217. }
  2218. class ZSetUnionStore extends Command {
  2219. public function getCommandId() { return 'ZUNIONSTORE'; }
  2220. public function filterArguments(Array $arguments) {
  2221. $options = array();
  2222. $argc = count($arguments);
  2223. if ($argc > 1 && is_array($arguments[$argc - 1])) {
  2224. $options = $this->prepareOptions(array_pop($arguments));
  2225. }
  2226. $args = is_array($arguments[0]) ? $arguments[0] : $arguments;
  2227. return array_merge($args, $options);
  2228. }
  2229. private function prepareOptions($options) {
  2230. $opts = array_change_key_case($options, CASE_UPPER);
  2231. $finalizedOpts = array();
  2232. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  2233. $finalizedOpts[] = 'WEIGHTS';
  2234. foreach ($opts['WEIGHTS'] as $weight) {
  2235. $finalizedOpts[] = $weight;
  2236. }
  2237. }
  2238. if (isset($opts['AGGREGATE'])) {
  2239. $finalizedOpts[] = 'AGGREGATE';
  2240. $finalizedOpts[] = $opts['AGGREGATE'];
  2241. }
  2242. return $finalizedOpts;
  2243. }
  2244. }
  2245. class ZSetIntersectionStore extends ZSetUnionStore {
  2246. public function getCommandId() { return 'ZINTERSTORE'; }
  2247. }
  2248. class ZSetRange extends Command {
  2249. private $_withScores = false;
  2250. public function getCommandId() { return 'ZRANGE'; }
  2251. public function filterArguments(Array $arguments) {
  2252. if (count($arguments) === 4) {
  2253. $lastType = gettype($arguments[3]);
  2254. if ($lastType === 'string' && strtolower($arguments[3]) === 'withscores') {
  2255. // used for compatibility with older versions
  2256. $arguments[3] = array('WITHSCORES' => true);
  2257. $lastType = 'array';
  2258. }
  2259. if ($lastType === 'array') {
  2260. $options = $this->prepareOptions(array_pop($arguments));
  2261. return array_merge($arguments, $options);
  2262. }
  2263. }
  2264. return $arguments;
  2265. }
  2266. protected function prepareOptions($options) {
  2267. $opts = array_change_key_case($options, CASE_UPPER);
  2268. $finalizedOpts = array();
  2269. if (isset($opts['WITHSCORES'])) {
  2270. $finalizedOpts[] = 'WITHSCORES';
  2271. $this->_withScores = true;
  2272. }
  2273. return $finalizedOpts;
  2274. }
  2275. public function parseResponse($data) {
  2276. if ($this->_withScores) {
  2277. if ($data instanceof \Iterator) {
  2278. return new MultiBulkResponseKVIterator($data);
  2279. }
  2280. $result = array();
  2281. for ($i = 0; $i < count($data); $i++) {
  2282. $result[] = array($data[$i], $data[++$i]);
  2283. }
  2284. return $result;
  2285. }
  2286. return $data;
  2287. }
  2288. }
  2289. class ZSetReverseRange extends ZSetRange {
  2290. public function getCommandId() { return 'ZREVRANGE'; }
  2291. }
  2292. class ZSetRangeByScore extends ZSetRange {
  2293. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  2294. protected function prepareOptions($options) {
  2295. $opts = array_change_key_case($options, CASE_UPPER);
  2296. $finalizedOpts = array();
  2297. if (isset($opts['LIMIT']) && is_array($opts['LIMIT'])) {
  2298. $limit = array_change_key_case($opts['LIMIT'], CASE_UPPER);
  2299. $finalizedOpts[] = 'LIMIT';
  2300. $finalizedOpts[] = isset($limit['OFFSET']) ? $limit['OFFSET'] : $limit[0];
  2301. $finalizedOpts[] = isset($limit['COUNT']) ? $limit['COUNT'] : $limit[1];
  2302. }
  2303. return array_merge($finalizedOpts, parent::prepareOptions($options));
  2304. }
  2305. }
  2306. class ZSetReverseRangeByScore extends ZSetRangeByScore {
  2307. public function getCommandId() { return 'ZREVRANGEBYSCORE'; }
  2308. }
  2309. class ZSetCount extends Command {
  2310. public function getCommandId() { return 'ZCOUNT'; }
  2311. }
  2312. class ZSetCardinality extends Command {
  2313. public function getCommandId() { return 'ZCARD'; }
  2314. }
  2315. class ZSetScore extends Command {
  2316. public function getCommandId() { return 'ZSCORE'; }
  2317. }
  2318. class ZSetRemoveRangeByScore extends Command {
  2319. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  2320. }
  2321. class ZSetRank extends Command {
  2322. public function getCommandId() { return 'ZRANK'; }
  2323. }
  2324. class ZSetReverseRank extends Command {
  2325. public function getCommandId() { return 'ZREVRANK'; }
  2326. }
  2327. class ZSetRemoveRangeByRank extends Command {
  2328. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  2329. }
  2330. /* commands operating on hashes */
  2331. class HashSet extends Command {
  2332. public function getCommandId() { return 'HSET'; }
  2333. public function parseResponse($data) { return (bool) $data; }
  2334. }
  2335. class HashSetPreserve extends Command {
  2336. public function getCommandId() { return 'HSETNX'; }
  2337. public function parseResponse($data) { return (bool) $data; }
  2338. }
  2339. class HashSetMultiple extends Command {
  2340. public function getCommandId() { return 'HMSET'; }
  2341. public function filterArguments(Array $arguments) {
  2342. if (count($arguments) === 2 && is_array($arguments[1])) {
  2343. $flattenedKVs = array($arguments[0]);
  2344. $args = &$arguments[1];
  2345. foreach ($args as $k => $v) {
  2346. $flattenedKVs[] = $k;
  2347. $flattenedKVs[] = $v;
  2348. }
  2349. return $flattenedKVs;
  2350. }
  2351. return $arguments;
  2352. }
  2353. }
  2354. class HashIncrementBy extends Command {
  2355. public function getCommandId() { return 'HINCRBY'; }
  2356. }
  2357. class HashGet extends Command {
  2358. public function getCommandId() { return 'HGET'; }
  2359. }
  2360. class HashGetMultiple extends Command {
  2361. public function getCommandId() { return 'HMGET'; }
  2362. public function filterArguments(Array $arguments) {
  2363. if (count($arguments) === 2 && is_array($arguments[1])) {
  2364. $flattenedKVs = array($arguments[0]);
  2365. $args = &$arguments[1];
  2366. foreach ($args as $v) {
  2367. $flattenedKVs[] = $v;
  2368. }
  2369. return $flattenedKVs;
  2370. }
  2371. return $arguments;
  2372. }
  2373. }
  2374. class HashDelete extends Command {
  2375. public function getCommandId() { return 'HDEL'; }
  2376. public function parseResponse($data) { return (bool) $data; }
  2377. }
  2378. class HashExists extends Command {
  2379. public function getCommandId() { return 'HEXISTS'; }
  2380. public function parseResponse($data) { return (bool) $data; }
  2381. }
  2382. class HashLength extends Command {
  2383. public function getCommandId() { return 'HLEN'; }
  2384. }
  2385. class HashKeys extends Command {
  2386. public function getCommandId() { return 'HKEYS'; }
  2387. }
  2388. class HashValues extends Command {
  2389. public function getCommandId() { return 'HVALS'; }
  2390. }
  2391. class HashGetAll extends Command {
  2392. public function getCommandId() { return 'HGETALL'; }
  2393. public function parseResponse($data) {
  2394. if ($data instanceof \Iterator) {
  2395. return new MultiBulkResponseKVIterator($data);
  2396. }
  2397. $result = array();
  2398. for ($i = 0; $i < count($data); $i++) {
  2399. $result[$data[$i]] = $data[++$i];
  2400. }
  2401. return $result;
  2402. }
  2403. }
  2404. /* multiple databases handling commands */
  2405. class SelectDatabase extends Command {
  2406. public function canBeHashed() { return false; }
  2407. public function getCommandId() { return 'SELECT'; }
  2408. }
  2409. class MoveKey extends Command {
  2410. public function canBeHashed() { return false; }
  2411. public function getCommandId() { return 'MOVE'; }
  2412. public function parseResponse($data) { return (bool) $data; }
  2413. }
  2414. class FlushDatabase extends Command {
  2415. public function canBeHashed() { return false; }
  2416. public function getCommandId() { return 'FLUSHDB'; }
  2417. }
  2418. class FlushAll extends Command {
  2419. public function canBeHashed() { return false; }
  2420. public function getCommandId() { return 'FLUSHALL'; }
  2421. }
  2422. /* sorting */
  2423. class Sort extends Command {
  2424. public function getCommandId() { return 'SORT'; }
  2425. public function filterArguments(Array $arguments) {
  2426. if (count($arguments) === 1) {
  2427. return $arguments;
  2428. }
  2429. $query = array($arguments[0]);
  2430. $sortParams = array_change_key_case($arguments[1], CASE_UPPER);
  2431. if (isset($sortParams['BY'])) {
  2432. $query[] = 'BY';
  2433. $query[] = $sortParams['BY'];
  2434. }
  2435. if (isset($sortParams['GET'])) {
  2436. $getargs = $sortParams['GET'];
  2437. if (is_array($getargs)) {
  2438. foreach ($getargs as $getarg) {
  2439. $query[] = 'GET';
  2440. $query[] = $getarg;
  2441. }
  2442. }
  2443. else {
  2444. $query[] = 'GET';
  2445. $query[] = $getargs;
  2446. }
  2447. }
  2448. if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
  2449. && count($sortParams['LIMIT']) == 2) {
  2450. $query[] = 'LIMIT';
  2451. $query[] = $sortParams['LIMIT'][0];
  2452. $query[] = $sortParams['LIMIT'][1];
  2453. }
  2454. if (isset($sortParams['SORT'])) {
  2455. $query[] = strtoupper($sortParams['SORT']);
  2456. }
  2457. if (isset($sortParams['ALPHA']) && $sortParams['ALPHA'] == true) {
  2458. $query[] = 'ALPHA';
  2459. }
  2460. if (isset($sortParams['STORE'])) {
  2461. $query[] = 'STORE';
  2462. $query[] = $sortParams['STORE'];
  2463. }
  2464. return $query;
  2465. }
  2466. }
  2467. /* transactions */
  2468. class Multi extends Command {
  2469. public function canBeHashed() { return false; }
  2470. public function getCommandId() { return 'MULTI'; }
  2471. }
  2472. class Exec extends Command {
  2473. public function canBeHashed() { return false; }
  2474. public function getCommandId() { return 'EXEC'; }
  2475. }
  2476. class Discard extends Command {
  2477. public function canBeHashed() { return false; }
  2478. public function getCommandId() { return 'DISCARD'; }
  2479. }
  2480. class Watch extends Command {
  2481. public function canBeHashed() { return false; }
  2482. public function getCommandId() { return 'WATCH'; }
  2483. public function filterArguments(Array $arguments) {
  2484. if (isset($arguments[0]) && is_array($arguments[0])) {
  2485. return $arguments[0];
  2486. }
  2487. return $arguments;
  2488. }
  2489. public function parseResponse($data) { return (bool) $data; }
  2490. }
  2491. class Unwatch extends Command {
  2492. public function canBeHashed() { return false; }
  2493. public function getCommandId() { return 'UNWATCH'; }
  2494. public function parseResponse($data) { return (bool) $data; }
  2495. }
  2496. /* publish/subscribe */
  2497. class Subscribe extends Command {
  2498. public function canBeHashed() { return false; }
  2499. public function getCommandId() { return 'SUBSCRIBE'; }
  2500. }
  2501. class Unsubscribe extends Command {
  2502. public function canBeHashed() { return false; }
  2503. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2504. }
  2505. class SubscribeByPattern extends Command {
  2506. public function canBeHashed() { return false; }
  2507. public function getCommandId() { return 'PSUBSCRIBE'; }
  2508. }
  2509. class UnsubscribeByPattern extends Command {
  2510. public function canBeHashed() { return false; }
  2511. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  2512. }
  2513. class Publish extends Command {
  2514. public function canBeHashed() { return false; }
  2515. public function getCommandId() { return 'PUBLISH'; }
  2516. }
  2517. /* persistence control commands */
  2518. class Save extends Command {
  2519. public function canBeHashed() { return false; }
  2520. public function getCommandId() { return 'SAVE'; }
  2521. }
  2522. class BackgroundSave extends Command {
  2523. public function canBeHashed() { return false; }
  2524. public function getCommandId() { return 'BGSAVE'; }
  2525. public function parseResponse($data) {
  2526. if ($data == 'Background saving started') {
  2527. return true;
  2528. }
  2529. return $data;
  2530. }
  2531. }
  2532. class BackgroundRewriteAppendOnlyFile extends Command {
  2533. public function canBeHashed() { return false; }
  2534. public function getCommandId() { return 'BGREWRITEAOF'; }
  2535. public function parseResponse($data) {
  2536. return $data == 'Background append only file rewriting started';
  2537. }
  2538. }
  2539. class LastSave extends Command {
  2540. public function canBeHashed() { return false; }
  2541. public function getCommandId() { return 'LASTSAVE'; }
  2542. }
  2543. class Shutdown extends Command {
  2544. public function canBeHashed() { return false; }
  2545. public function getCommandId() { return 'SHUTDOWN'; }
  2546. public function closesConnection() { return true; }
  2547. }
  2548. /* remote server control commands */
  2549. class Info extends Command {
  2550. public function canBeHashed() { return false; }
  2551. public function getCommandId() { return 'INFO'; }
  2552. public function parseResponse($data) {
  2553. $info = array();
  2554. $infoLines = explode("\r\n", $data, -1);
  2555. foreach ($infoLines as $row) {
  2556. list($k, $v) = explode(':', $row);
  2557. if (!preg_match('/^db\d+$/', $k)) {
  2558. $info[$k] = $v;
  2559. }
  2560. else {
  2561. $db = array();
  2562. foreach (explode(',', $v) as $dbvar) {
  2563. list($dbvk, $dbvv) = explode('=', $dbvar);
  2564. $db[trim($dbvk)] = $dbvv;
  2565. }
  2566. $info[$k] = $db;
  2567. }
  2568. }
  2569. return $info;
  2570. }
  2571. }
  2572. class SlaveOf extends Command {
  2573. public function canBeHashed() { return false; }
  2574. public function getCommandId() { return 'SLAVEOF'; }
  2575. public function filterArguments(Array $arguments) {
  2576. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2577. return array('NO', 'ONE');
  2578. }
  2579. return $arguments;
  2580. }
  2581. }
  2582. class Config extends Command {
  2583. public function canBeHashed() { return false; }
  2584. public function getCommandId() { return 'CONFIG'; }
  2585. }
  2586. ?>