Predis.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { }
  5. class ServerException extends PredisException { }
  6. class MalformedServerResponse extends ServerException { }
  7. /* ------------------------------------------------------------------------- */
  8. class Client {
  9. private $_connection, $_serverProfile, $_responseReader;
  10. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  11. $this->_responseReader = new ResponseReader();
  12. $this->setProfile($serverProfile ?: RedisServerProfile::getDefault());
  13. $this->setupConnection($parameters);
  14. }
  15. public function __destruct() {
  16. $this->_connection->disconnect();
  17. }
  18. public static function create(/* arguments */) {
  19. $argv = func_get_args();
  20. $argc = func_num_args();
  21. $serverProfile = null;
  22. $lastArg = $argv[$argc-1];
  23. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  24. $serverProfile = array_pop($argv);
  25. $argc--;
  26. }
  27. if ($argc === 0) {
  28. throw new ClientException('Missing connection parameters');
  29. }
  30. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  31. }
  32. private function setupConnection($parameters) {
  33. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  34. throw new ClientException('Invalid parameters type (array or string expected)');
  35. }
  36. if (is_array($parameters) && isset($parameters[0])) {
  37. $cluster = new ConnectionCluster();
  38. foreach ($parameters as $shardParams) {
  39. $cluster->add($this->createConnection($shardParams));
  40. }
  41. $this->setConnection($cluster);
  42. }
  43. else {
  44. $this->setConnection($this->createConnection($parameters));
  45. }
  46. }
  47. private function createConnection($parameters) {
  48. $params = new ConnectionParameters($parameters);
  49. $connection = new Connection($params, $this->_responseReader);
  50. if ($params->password !== null) {
  51. $connection->pushInitCommand($this->createCommand(
  52. 'auth', array($params->password)
  53. ));
  54. }
  55. if ($params->database !== null) {
  56. $connection->pushInitCommand($this->createCommand(
  57. 'select', array($params->database)
  58. ));
  59. }
  60. return $connection;
  61. }
  62. private function setConnection(IConnection $connection) {
  63. $this->_connection = $connection;
  64. }
  65. public function setProfile(RedisServerProfile $serverProfile) {
  66. $this->_serverProfile = $serverProfile;
  67. }
  68. public function getProfile() {
  69. return $this->_serverProfile;
  70. }
  71. public function getResponseReader() {
  72. return $this->_responseReader;
  73. }
  74. public function connect() {
  75. $this->_connection->connect();
  76. }
  77. public function disconnect() {
  78. $this->_connection->disconnect();
  79. }
  80. public function isConnected() {
  81. return $this->_connection->isConnected();
  82. }
  83. public function getConnection($id = null) {
  84. if (!isset($id)) {
  85. return $this->_connection;
  86. }
  87. else {
  88. return $this->_connection instanceof ConnectionCluster
  89. ? $this->_connection->getConnectionById($id)
  90. : $this->_connection;
  91. }
  92. }
  93. public function __call($method, $arguments) {
  94. $command = $this->_serverProfile->createCommand($method, $arguments);
  95. return $this->_connection->executeCommand($command);
  96. }
  97. public function createCommand($method, $arguments = array()) {
  98. return $this->_serverProfile->createCommand($method, $arguments);
  99. }
  100. public function executeCommand(Command $command) {
  101. return $this->_connection->executeCommand($command);
  102. }
  103. public function executeCommandOnShards(Command $command) {
  104. $replies = array();
  105. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  106. foreach($this->_connection as $connection) {
  107. $replies[] = $connection->executeCommand($command);
  108. }
  109. }
  110. else {
  111. $replies[] = $this->_connection->executeCommand($command);
  112. }
  113. return $replies;
  114. }
  115. public function rawCommand($rawCommandData, $closesConnection = false) {
  116. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  117. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  118. }
  119. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  120. }
  121. public function pipeline($pipelineBlock = null) {
  122. $pipeline = new CommandPipeline($this);
  123. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  124. }
  125. public function multiExec($multiExecBlock = null) {
  126. $multiExec = new MultiExecBlock($this);
  127. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  128. }
  129. }
  130. /* ------------------------------------------------------------------------- */
  131. abstract class Command {
  132. private $_arguments, $_hash;
  133. public abstract function getCommandId();
  134. public abstract function serializeRequest($command, $arguments);
  135. public function canBeHashed() {
  136. return true;
  137. }
  138. public function getHash() {
  139. if (isset($this->_hash)) {
  140. return $this->_hash;
  141. }
  142. else {
  143. if (isset($this->_arguments[0])) {
  144. $key = $this->_arguments[0];
  145. $start = strpos($key, '{');
  146. $end = strpos($key, '}');
  147. if ($start !== false && $end !== false) {
  148. $key = substr($key, ++$start, $end - $start);
  149. }
  150. $this->_hash = crc32($key);
  151. return $this->_hash;
  152. }
  153. }
  154. return null;
  155. }
  156. public function closesConnection() {
  157. return false;
  158. }
  159. protected function filterArguments(Array $arguments) {
  160. return $arguments;
  161. }
  162. public function setArguments(/* arguments */) {
  163. $this->_arguments = $this->filterArguments(func_get_args());
  164. }
  165. public function setArgumentsArray(Array $arguments) {
  166. $this->_arguments = $this->filterArguments($arguments);
  167. }
  168. protected function getArguments() {
  169. // TODO: why getArguments is protected?
  170. return isset($this->_arguments) ? $this->_arguments : array();
  171. }
  172. public function getArgument($index = 0) {
  173. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  174. }
  175. public function parseResponse($data) {
  176. return $data;
  177. }
  178. public final function __invoke() {
  179. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  180. }
  181. }
  182. abstract class InlineCommand extends Command {
  183. public function serializeRequest($command, $arguments) {
  184. if (isset($arguments[0]) && is_array($arguments[0])) {
  185. $arguments[0] = implode($arguments[0], ' ');
  186. }
  187. return $command . ' ' . implode($arguments, ' ') . ResponseReader::NEWLINE;
  188. }
  189. }
  190. abstract class BulkCommand extends Command {
  191. public function serializeRequest($command, $arguments) {
  192. $data = array_pop($arguments);
  193. if (is_array($data)) {
  194. $data = implode($data, ' ');
  195. }
  196. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  197. ResponseReader::NEWLINE . $data . ResponseReader::NEWLINE;
  198. }
  199. }
  200. abstract class MultiBulkCommand extends Command {
  201. public function serializeRequest($command, $arguments) {
  202. $buffer = array();
  203. $cmd_args = null;
  204. if (count($arguments) === 1 && is_array($arguments[0])) {
  205. $cmd_args = array();
  206. foreach ($arguments[0] as $k => $v) {
  207. $cmd_args[] = $k;
  208. $cmd_args[] = $v;
  209. }
  210. }
  211. else {
  212. $cmd_args = $arguments;
  213. }
  214. $buffer[] = '*' . ((string) count($cmd_args) + 1) . ResponseReader::NEWLINE;
  215. $buffer[] = '$' . strlen($command) . ResponseReader::NEWLINE . $command . ResponseReader::NEWLINE;
  216. foreach ($cmd_args as $argument) {
  217. $buffer[] = '$' . strlen($argument) . ResponseReader::NEWLINE . $argument . ResponseReader::NEWLINE;
  218. }
  219. return implode('', $buffer);
  220. }
  221. }
  222. /* ------------------------------------------------------------------------- */
  223. interface IResponseHandler {
  224. function handle(Connection $connection, $payload);
  225. }
  226. class ResponseStatusHandler implements IResponseHandler {
  227. public function handle(Connection $connection, $status) {
  228. if ($status === ResponseReader::OK) {
  229. return true;
  230. }
  231. else if ($status === ResponseReader::QUEUED) {
  232. return new ResponseQueued();
  233. }
  234. return $status;
  235. }
  236. }
  237. class ResponseErrorHandler implements IResponseHandler {
  238. public function handle(Connection $connection, $errorMessage) {
  239. throw new ServerException(substr($errorMessage, 4));
  240. }
  241. }
  242. class ResponseErrorSilentHandler implements IResponseHandler {
  243. public function handle(Connection $connection, $errorMessage) {
  244. return new ResponseError(substr($errorMessage, 4));
  245. }
  246. }
  247. class ResponseBulkHandler implements IResponseHandler {
  248. public function handle(Connection $connection, $dataLength) {
  249. $socket = $connection->getSocket();
  250. if (!is_numeric($dataLength)) {
  251. throw new ClientException("Cannot parse '$dataLength' as data length");
  252. }
  253. if ($dataLength > 0) {
  254. $value = stream_get_contents($socket, $dataLength);
  255. if ($value === false) {
  256. throw new ClientException('An error has occurred while reading from the network stream');
  257. }
  258. fread($socket, 2);
  259. return $value;
  260. }
  261. else if ($dataLength == 0) {
  262. fread($socket, 2);
  263. return '';
  264. }
  265. return null;
  266. }
  267. }
  268. class ResponseMultiBulkHandler implements IResponseHandler {
  269. public function handle(Connection $connection, $rawLength) {
  270. if (!is_numeric($rawLength)) {
  271. throw new ClientException("Cannot parse '$rawLength' as data length");
  272. }
  273. $listLength = (int) $rawLength;
  274. if ($listLength === -1) {
  275. return null;
  276. }
  277. $list = array();
  278. if ($listLength > 0) {
  279. for ($i = 0; $i < $listLength; $i++) {
  280. $list[] = $connection->getResponseReader()->read($connection);
  281. }
  282. }
  283. return $list;
  284. }
  285. }
  286. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  287. public function handle(Connection $connection, $rawLength) {
  288. if (!is_numeric($rawLength)) {
  289. throw new ClientException("Cannot parse '$rawLength' as data length");
  290. }
  291. return new Utilities\MultiBulkResponseIterator($connection, (int)$rawLength);
  292. }
  293. }
  294. class ResponseIntegerHandler implements IResponseHandler {
  295. public function handle(Connection $connection, $number) {
  296. if (is_numeric($number)) {
  297. return (int) $number;
  298. }
  299. else {
  300. if ($number !== ResponseReader::NULL) {
  301. throw new ClientException("Cannot parse '$number' as numeric response");
  302. }
  303. return null;
  304. }
  305. }
  306. }
  307. class ResponseReader {
  308. const NEWLINE = "\r\n";
  309. const OK = 'OK';
  310. const ERROR = 'ERR';
  311. const QUEUED = 'QUEUED';
  312. const NULL = 'nil';
  313. const PREFIX_STATUS = '+';
  314. const PREFIX_ERROR = '-';
  315. const PREFIX_INTEGER = ':';
  316. const PREFIX_BULK = '$';
  317. const PREFIX_MULTI_BULK = '*';
  318. private $_prefixHandlers;
  319. public function __construct() {
  320. $this->initializePrefixHandlers();
  321. }
  322. private function initializePrefixHandlers() {
  323. $this->_prefixHandlers = array(
  324. self::PREFIX_STATUS => new ResponseStatusHandler(),
  325. self::PREFIX_ERROR => new ResponseErrorHandler(),
  326. self::PREFIX_INTEGER => new ResponseIntegerHandler(),
  327. self::PREFIX_BULK => new ResponseBulkHandler(),
  328. self::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  329. );
  330. }
  331. private function setHandler($prefix, IResponseHandler $handler) {
  332. $this->_prefixHandlers[$prefix] = $handler;
  333. }
  334. public function setOption($option, $value) {
  335. switch ($option) {
  336. case 'iterable_multibulk_replies':
  337. case 'iterableMultiBulkReplies':
  338. $this->setHandler(self::PREFIX_MULTI_BULK, $value == true
  339. ? new ResponseMultiBulkStreamHandler()
  340. : new ResponseMultiBulkHandler()
  341. );
  342. break;
  343. case 'errorThrowException':
  344. case 'error_throw_exception':
  345. $this->setHandler(self::PREFIX_ERROR, $value == true
  346. ? new ResponseErrorHandler()
  347. : new ResponseErrorSilentHandler()
  348. );
  349. break;
  350. default:
  351. throw new \InvalidArgumentException("Unknown option: $option");
  352. }
  353. }
  354. public function getOption($option) {
  355. switch ($option) {
  356. case 'iterable_multibulk_replies':
  357. case 'iterableMultiBulkReplies':
  358. return $this->_prefixHandlers[self::PREFIX_MULTI_BULK]
  359. instanceof ResponseMultiBulkStreamHandler;
  360. case 'errorThrowException':
  361. case 'error_throw_exception':
  362. return $this->_prefixHandlers[self::PREFIX_ERROR]
  363. instanceof ResponseErrorHandler;
  364. default:
  365. throw new \InvalidArgumentException("Unknown option: $option");
  366. }
  367. }
  368. public function read(Connection $connection) {
  369. $header = fgets($connection->getSocket());
  370. if ($header === false) {
  371. throw new ClientException('An error has occurred while reading from the network stream');
  372. }
  373. $prefix = $header[0];
  374. $payload = substr($header, 1, -2);
  375. if (!isset($this->_prefixHandlers[$prefix])) {
  376. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  377. }
  378. $handler = $this->_prefixHandlers[$prefix];
  379. return $handler->handle($connection, $payload);
  380. }
  381. }
  382. class ResponseError {
  383. private $_message;
  384. public function __construct($message) {
  385. $this->_message = $message;
  386. }
  387. public function __get($property) {
  388. if ($property == 'error') {
  389. return true;
  390. }
  391. if ($property == 'message') {
  392. return $this->_message;
  393. }
  394. }
  395. public function __isset($property) {
  396. return $property === 'error';
  397. }
  398. public function __toString() {
  399. return $this->_message;
  400. }
  401. }
  402. class ResponseQueued {
  403. public $queued = true;
  404. public function __toString() {
  405. return ResponseReader::QUEUED;
  406. }
  407. }
  408. /* ------------------------------------------------------------------------- */
  409. class CommandPipeline {
  410. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  411. public function __construct(Client $redisClient) {
  412. $this->_redisClient = $redisClient;
  413. $this->_pipelineBuffer = array();
  414. $this->_returnValues = array();
  415. }
  416. public function __call($method, $arguments) {
  417. $command = $this->_redisClient->createCommand($method, $arguments);
  418. $this->recordCommand($command);
  419. return $this;
  420. }
  421. private function recordCommand(Command $command) {
  422. $this->_pipelineBuffer[] = $command;
  423. }
  424. private function getRecordedCommands() {
  425. return $this->_pipelineBuffer;
  426. }
  427. public function flushPipeline() {
  428. $sizeofPipe = count($this->_pipelineBuffer);
  429. if ($sizeofPipe === 0) {
  430. return;
  431. }
  432. $connection = $this->_redisClient->getConnection();
  433. $commands = &$this->_pipelineBuffer;
  434. foreach ($commands as $command) {
  435. $connection->writeCommand($command);
  436. }
  437. for ($i = 0; $i < $sizeofPipe; $i++) {
  438. $response = $connection->readResponse($commands[$i]);
  439. $this->_returnValues[] = ($response instanceof \Iterator
  440. ? iterator_to_array($response)
  441. : $response
  442. );
  443. unset($commands[$i]);
  444. }
  445. $this->_pipelineBuffer = array();
  446. return $this;
  447. }
  448. private function setRunning($bool) {
  449. if ($bool == true && $this->_running == true) {
  450. throw new ClientException("This pipeline is already opened");
  451. }
  452. $this->_running = $bool;
  453. }
  454. public function execute($block = null) {
  455. if ($block && !is_callable($block)) {
  456. throw new \RuntimeException('Argument passed must be a callable object');
  457. }
  458. // TODO: do not reuse previously executed pipelines
  459. $this->setRunning(true);
  460. $pipelineBlockException = null;
  461. try {
  462. if ($block !== null) {
  463. $block($this);
  464. }
  465. $this->flushPipeline();
  466. }
  467. catch (\Exception $exception) {
  468. // TODO: client/server desync on ServerException
  469. $pipelineBlockException = $exception;
  470. }
  471. $this->setRunning(false);
  472. if ($pipelineBlockException !== null) {
  473. throw $pipelineBlockException;
  474. }
  475. return $this->_returnValues;
  476. }
  477. }
  478. class MultiExecBlock {
  479. private $_redisClient, $_commands, $_initialized, $_discarded;
  480. public function __construct(Client $redisClient) {
  481. $this->_initialized = false;
  482. $this->_discarded = false;
  483. $this->_redisClient = $redisClient;
  484. $this->_commands = array();
  485. }
  486. private function initialize() {
  487. if ($this->_initialized === false) {
  488. $this->_redisClient->multi();
  489. $this->_initialized = true;
  490. $this->_discarded = false;
  491. }
  492. }
  493. public function __call($method, $arguments) {
  494. $this->initialize();
  495. $command = $this->_redisClient->createCommand($method, $arguments);
  496. $response = $this->_redisClient->executeCommand($command);
  497. if (isset($response->queued)) {
  498. $this->_commands[] = $command;
  499. return $this;
  500. }
  501. else {
  502. throw new ClientException('The server did not respond with a QUEUED status reply');
  503. }
  504. }
  505. public function discard() {
  506. $this->_redisClient->discard();
  507. $this->_commands = array();
  508. $this->_initialized = false;
  509. $this->_discarded = true;
  510. }
  511. public function execute($block = null) {
  512. if ($block && !is_callable($block)) {
  513. throw new \RuntimeException('Argument passed must be a callable object');
  514. }
  515. $blockException = null;
  516. $returnValues = array();
  517. try {
  518. if ($block !== null) {
  519. $block($this);
  520. }
  521. if ($this->_discarded === true) {
  522. return;
  523. }
  524. $execReply = (($reply = $this->_redisClient->exec()) instanceof \Iterator
  525. ? iterator_to_array($reply)
  526. : $reply
  527. );
  528. $commands = &$this->_commands;
  529. $sizeofReplies = count($execReply);
  530. if ($sizeofReplies !== count($commands)) {
  531. // TODO: think of a better exception message
  532. throw new ClientException("Out-of-sync");
  533. }
  534. for ($i = 0; $i < $sizeofReplies; $i++) {
  535. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  536. ? iterator_to_array($execReply[$i])
  537. : $execReply[$i]
  538. );
  539. unset($commands[$i]);
  540. }
  541. }
  542. catch (\Exception $exception) {
  543. $blockException = $exception;
  544. }
  545. if ($blockException !== null) {
  546. throw $blockException;
  547. }
  548. return $returnValues;
  549. }
  550. }
  551. /* ------------------------------------------------------------------------- */
  552. class ConnectionParameters {
  553. const DEFAULT_HOST = '127.0.0.1';
  554. const DEFAULT_PORT = 6379;
  555. const DEFAULT_TIMEOUT = 5;
  556. private $_parameters;
  557. public function __construct($parameters = null) {
  558. $parameters = $parameters ?: array();
  559. $this->_parameters = is_array($parameters)
  560. ? self::filterConnectionParams($parameters)
  561. : self::parseURI($parameters);
  562. }
  563. private static function parseURI($uri) {
  564. $parsed = @parse_url($uri);
  565. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  566. throw new ClientException("Invalid URI: $uri");
  567. }
  568. if (array_key_exists('query', $parsed)) {
  569. $details = array();
  570. foreach (explode('&', $parsed['query']) as $kv) {
  571. list($k, $v) = explode('=', $kv);
  572. switch ($k) {
  573. case 'database':
  574. $details['database'] = $v;
  575. break;
  576. case 'password':
  577. $details['password'] = $v;
  578. break;
  579. case 'connection_timeout':
  580. $details['connection_timeout'] = $v;
  581. break;
  582. case 'read_write_timeout':
  583. $details['read_write_timeout'] = $v;
  584. break;
  585. case 'alias':
  586. $details['alias'] = $v;
  587. break;
  588. }
  589. }
  590. $parsed = array_merge($parsed, $details);
  591. }
  592. return self::filterConnectionParams($parsed);
  593. }
  594. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  595. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  596. }
  597. private static function filterConnectionParams($parameters) {
  598. return array(
  599. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  600. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  601. 'database' => self::getParamOrDefault($parameters, 'database'),
  602. 'password' => self::getParamOrDefault($parameters, 'password'),
  603. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  604. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  605. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  606. );
  607. }
  608. public function __get($parameter) {
  609. return $this->_parameters[$parameter];
  610. }
  611. public function __isset($parameter) {
  612. return isset($this->_parameters[$parameter]);
  613. }
  614. }
  615. interface IConnection {
  616. public function connect();
  617. public function disconnect();
  618. public function isConnected();
  619. public function writeCommand(Command $command);
  620. public function readResponse(Command $command);
  621. public function executeCommand(Command $command);
  622. }
  623. class Connection implements IConnection {
  624. private $_params, $_socket, $_initCmds, $_reader;
  625. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  626. $this->_params = $parameters;
  627. $this->_initCmds = array();
  628. $this->_reader = $reader ?: new ResponseReader();
  629. }
  630. public function __destruct() {
  631. $this->disconnect();
  632. }
  633. public function isConnected() {
  634. return is_resource($this->_socket);
  635. }
  636. public function connect() {
  637. if ($this->isConnected()) {
  638. throw new ClientException('Connection already estabilished');
  639. }
  640. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  641. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $this->_params->connection_timeout);
  642. if (!$this->_socket) {
  643. throw new ClientException(trim($errstr), $errno);
  644. }
  645. if (isset($this->_params->read_write_timeout)) {
  646. $timeoutSeconds = floor($this->_params->read_write_timeout);
  647. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  648. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  649. }
  650. if (count($this->_initCmds) > 0){
  651. $this->sendInitializationCommands();
  652. }
  653. }
  654. public function disconnect() {
  655. if ($this->isConnected()) {
  656. fclose($this->_socket);
  657. }
  658. }
  659. public function pushInitCommand(Command $command){
  660. $this->_initCmds[] = $command;
  661. }
  662. private function sendInitializationCommands() {
  663. foreach ($this->_initCmds as $command) {
  664. $this->writeCommand($command);
  665. }
  666. foreach ($this->_initCmds as $command) {
  667. $this->readResponse($command);
  668. }
  669. }
  670. public function writeCommand(Command $command) {
  671. $written = fwrite($this->getSocket(), $command());
  672. if ($written === false){
  673. throw new ClientException(sprintf(
  674. 'An error has occurred while writing command %s on the network stream',
  675. $command->getCommandId()
  676. ));
  677. }
  678. }
  679. public function readResponse(Command $command) {
  680. $response = $this->_reader->read($this);
  681. $skipparse = isset($response->queued) || isset($response->error);
  682. return $skipparse ? $response : $command->parseResponse($response);
  683. }
  684. public function executeCommand(Command $command) {
  685. $this->writeCommand($command);
  686. if ($command->closesConnection()) {
  687. return $this->disconnect();
  688. }
  689. return $this->readResponse($command);
  690. }
  691. public function rawCommand($rawCommandData, $closesConnection = false) {
  692. $socket = $this->getSocket();
  693. $written = fwrite($socket, $rawCommandData);
  694. if ($written === false){
  695. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  696. }
  697. if ($closesConnection) {
  698. return;
  699. }
  700. return $this->_reader->read($this);
  701. }
  702. public function getSocket() {
  703. if (!$this->isConnected()) {
  704. $this->connect();
  705. }
  706. return $this->_socket;
  707. }
  708. public function getResponseReader() {
  709. return $this->_reader;
  710. }
  711. public function getAlias() {
  712. return $this->_params->alias;
  713. }
  714. public function __toString() {
  715. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  716. }
  717. }
  718. class ConnectionCluster implements IConnection, \IteratorAggregate {
  719. private $_pool, $_ring;
  720. public function __construct() {
  721. $this->_pool = array();
  722. $this->_ring = new Utilities\HashRing();
  723. }
  724. public function __destruct() {
  725. $this->disconnect();
  726. }
  727. public function isConnected() {
  728. foreach ($this->_pool as $connection) {
  729. if ($connection->isConnected()) {
  730. return true;
  731. }
  732. }
  733. return false;
  734. }
  735. public function connect() {
  736. foreach ($this->_pool as $connection) {
  737. $connection->connect();
  738. }
  739. }
  740. public function disconnect() {
  741. foreach ($this->_pool as $connection) {
  742. $connection->disconnect();
  743. }
  744. }
  745. public function add(Connection $connection) {
  746. $connectionAlias = $connection->getAlias();
  747. if (isset($connectionAlias)) {
  748. $this->_pool[$connectionAlias] = $connection;
  749. }
  750. else {
  751. $this->_pool[] = $connection;
  752. }
  753. $this->_ring->add($connection);
  754. }
  755. public function getConnection(Command $command) {
  756. if ($command->canBeHashed() === false) {
  757. throw new ClientException(
  758. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  759. );
  760. }
  761. return $this->_ring->get($command->getHash());
  762. }
  763. public function getConnectionById($id = null) {
  764. return $this->_pool[$id ?: 0];
  765. }
  766. public function getIterator() {
  767. return new \ArrayIterator($this->_pool);
  768. }
  769. public function writeCommand(Command $command) {
  770. $this->getConnection($command)->writeCommand($command);
  771. }
  772. public function readResponse(Command $command) {
  773. return $this->getConnection($command)->readResponse($command);
  774. }
  775. public function executeCommand(Command $command) {
  776. $connection = $this->getConnection($command);
  777. $connection->writeCommand($command);
  778. return $connection->readResponse($command);
  779. }
  780. }
  781. /* ------------------------------------------------------------------------- */
  782. abstract class RedisServerProfile {
  783. private static $_serverProfiles;
  784. private $_registeredCommands;
  785. public function __construct() {
  786. $this->_registeredCommands = $this->getSupportedCommands();
  787. }
  788. public abstract function getVersion();
  789. protected abstract function getSupportedCommands();
  790. public static function getDefault() {
  791. return self::get('default');
  792. }
  793. private static function predisServerProfiles() {
  794. return array(
  795. '1.0' => '\Predis\RedisServer_v1_0',
  796. '1.2' => '\Predis\RedisServer_v1_2',
  797. 'default' => '\Predis\RedisServer_v1_2',
  798. 'dev' => '\Predis\RedisServer_vNext',
  799. );
  800. }
  801. public static function get($version) {
  802. if (!isset(self::$_serverProfiles)) {
  803. self::$_serverProfiles = self::predisServerProfiles();
  804. }
  805. if (!isset(self::$_serverProfiles[$version])) {
  806. throw new ClientException("Unknown server profile: $version");
  807. }
  808. $profile = self::$_serverProfiles[$version];
  809. return new $profile();
  810. }
  811. public function compareWith($version, $operator = null) {
  812. // one could expect that PHP's version_compare would behave
  813. // the same way if invoked with 2 arguments or 3 arguments
  814. // with the third being NULL, but it is not like that.
  815. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  816. // we might need to revise the behavior of this method.
  817. return ($operator === null
  818. ? version_compare($this, $version)
  819. : version_compare($this, $version, $operator)
  820. );
  821. }
  822. public function supportsCommand($command) {
  823. return isset($this->_registeredCommands[$command]);
  824. }
  825. public function createCommand($method, $arguments = array()) {
  826. if (!isset($this->_registeredCommands[$method])) {
  827. throw new ClientException("'$method' is not a registered Redis command");
  828. }
  829. $commandClass = $this->_registeredCommands[$method];
  830. $command = new $commandClass();
  831. $command->setArgumentsArray($arguments);
  832. return $command;
  833. }
  834. public function registerCommands(Array $commands) {
  835. foreach ($commands as $command => $aliases) {
  836. $this->registerCommand($command, $aliases);
  837. }
  838. }
  839. public function registerCommand($command, $aliases) {
  840. $commandReflection = new \ReflectionClass($command);
  841. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  842. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  843. }
  844. if (is_array($aliases)) {
  845. foreach ($aliases as $alias) {
  846. $this->_registeredCommands[$alias] = $command;
  847. }
  848. }
  849. else {
  850. $this->_registeredCommands[$aliases] = $command;
  851. }
  852. }
  853. public function __toString() {
  854. return $this->getVersion();
  855. }
  856. }
  857. class RedisServer_v1_0 extends RedisServerProfile {
  858. public function getVersion() { return '1.0'; }
  859. public function getSupportedCommands() {
  860. return array(
  861. /* miscellaneous commands */
  862. 'ping' => '\Predis\Commands\Ping',
  863. 'echo' => '\Predis\Commands\DoEcho',
  864. 'auth' => '\Predis\Commands\Auth',
  865. /* connection handling */
  866. 'quit' => '\Predis\Commands\Quit',
  867. /* commands operating on string values */
  868. 'set' => '\Predis\Commands\Set',
  869. 'setnx' => '\Predis\Commands\SetPreserve',
  870. 'setPreserve' => '\Predis\Commands\SetPreserve',
  871. 'get' => '\Predis\Commands\Get',
  872. 'mget' => '\Predis\Commands\GetMultiple',
  873. 'getMultiple' => '\Predis\Commands\GetMultiple',
  874. 'getset' => '\Predis\Commands\GetSet',
  875. 'getSet' => '\Predis\Commands\GetSet',
  876. 'incr' => '\Predis\Commands\Increment',
  877. 'increment' => '\Predis\Commands\Increment',
  878. 'incrby' => '\Predis\Commands\IncrementBy',
  879. 'incrementBy' => '\Predis\Commands\IncrementBy',
  880. 'decr' => '\Predis\Commands\Decrement',
  881. 'decrement' => '\Predis\Commands\Decrement',
  882. 'decrby' => '\Predis\Commands\DecrementBy',
  883. 'decrementBy' => '\Predis\Commands\DecrementBy',
  884. 'exists' => '\Predis\Commands\Exists',
  885. 'del' => '\Predis\Commands\Delete',
  886. 'delete' => '\Predis\Commands\Delete',
  887. 'type' => '\Predis\Commands\Type',
  888. /* commands operating on the key space */
  889. 'keys' => '\Predis\Commands\Keys',
  890. 'randomkey' => '\Predis\Commands\RandomKey',
  891. 'randomKey' => '\Predis\Commands\RandomKey',
  892. 'rename' => '\Predis\Commands\Rename',
  893. 'renamenx' => '\Predis\Commands\RenamePreserve',
  894. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  895. 'expire' => '\Predis\Commands\Expire',
  896. 'expireat' => '\Predis\Commands\ExpireAt',
  897. 'expireAt' => '\Predis\Commands\ExpireAt',
  898. 'dbsize' => '\Predis\Commands\DatabaseSize',
  899. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  900. 'ttl' => '\Predis\Commands\TimeToLive',
  901. 'timeToLive' => '\Predis\Commands\TimeToLive',
  902. /* commands operating on lists */
  903. 'rpush' => '\Predis\Commands\ListPushTail',
  904. 'pushTail' => '\Predis\Commands\ListPushTail',
  905. 'lpush' => '\Predis\Commands\ListPushHead',
  906. 'pushHead' => '\Predis\Commands\ListPushHead',
  907. 'llen' => '\Predis\Commands\ListLength',
  908. 'listLength' => '\Predis\Commands\ListLength',
  909. 'lrange' => '\Predis\Commands\ListRange',
  910. 'listRange' => '\Predis\Commands\ListRange',
  911. 'ltrim' => '\Predis\Commands\ListTrim',
  912. 'listTrim' => '\Predis\Commands\ListTrim',
  913. 'lindex' => '\Predis\Commands\ListIndex',
  914. 'listIndex' => '\Predis\Commands\ListIndex',
  915. 'lset' => '\Predis\Commands\ListSet',
  916. 'listSet' => '\Predis\Commands\ListSet',
  917. 'lrem' => '\Predis\Commands\ListRemove',
  918. 'listRemove' => '\Predis\Commands\ListRemove',
  919. 'lpop' => '\Predis\Commands\ListPopFirst',
  920. 'popFirst' => '\Predis\Commands\ListPopFirst',
  921. 'rpop' => '\Predis\Commands\ListPopLast',
  922. 'popLast' => '\Predis\Commands\ListPopLast',
  923. /* commands operating on sets */
  924. 'sadd' => '\Predis\Commands\SetAdd',
  925. 'setAdd' => '\Predis\Commands\SetAdd',
  926. 'srem' => '\Predis\Commands\SetRemove',
  927. 'setRemove' => '\Predis\Commands\SetRemove',
  928. 'spop' => '\Predis\Commands\SetPop',
  929. 'setPop' => '\Predis\Commands\SetPop',
  930. 'smove' => '\Predis\Commands\SetMove',
  931. 'setMove' => '\Predis\Commands\SetMove',
  932. 'scard' => '\Predis\Commands\SetCardinality',
  933. 'setCardinality' => '\Predis\Commands\SetCardinality',
  934. 'sismember' => '\Predis\Commands\SetIsMember',
  935. 'setIsMember' => '\Predis\Commands\SetIsMember',
  936. 'sinter' => '\Predis\Commands\SetIntersection',
  937. 'setIntersection' => '\Predis\Commands\SetIntersection',
  938. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  939. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  940. 'sunion' => '\Predis\Commands\SetUnion',
  941. 'setUnion' => '\Predis\Commands\SetUnion',
  942. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  943. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  944. 'sdiff' => '\Predis\Commands\SetDifference',
  945. 'setDifference' => '\Predis\Commands\SetDifference',
  946. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  947. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  948. 'smembers' => '\Predis\Commands\SetMembers',
  949. 'setMembers' => '\Predis\Commands\SetMembers',
  950. 'srandmember' => '\Predis\Commands\SetRandomMember',
  951. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  952. /* multiple databases handling commands */
  953. 'select' => '\Predis\Commands\SelectDatabase',
  954. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  955. 'move' => '\Predis\Commands\MoveKey',
  956. 'moveKey' => '\Predis\Commands\MoveKey',
  957. 'flushdb' => '\Predis\Commands\FlushDatabase',
  958. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  959. 'flushall' => '\Predis\Commands\FlushAll',
  960. 'flushDatabases' => '\Predis\Commands\FlushAll',
  961. /* sorting */
  962. 'sort' => '\Predis\Commands\Sort',
  963. /* remote server control commands */
  964. 'info' => '\Predis\Commands\Info',
  965. 'slaveof' => '\Predis\Commands\SlaveOf',
  966. 'slaveOf' => '\Predis\Commands\SlaveOf',
  967. /* persistence control commands */
  968. 'save' => '\Predis\Commands\Save',
  969. 'bgsave' => '\Predis\Commands\BackgroundSave',
  970. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  971. 'lastsave' => '\Predis\Commands\LastSave',
  972. 'lastSave' => '\Predis\Commands\LastSave',
  973. 'shutdown' => '\Predis\Commands\Shutdown',
  974. );
  975. }
  976. }
  977. class RedisServer_v1_2 extends RedisServer_v1_0 {
  978. public function getVersion() { return '1.2'; }
  979. public function getSupportedCommands() {
  980. return array_merge(parent::getSupportedCommands(), array(
  981. /* commands operating on string values */
  982. 'mset' => '\Predis\Commands\SetMultiple',
  983. 'setMultiple' => '\Predis\Commands\SetMultiple',
  984. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  985. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  986. /* commands operating on lists */
  987. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  988. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  989. /* commands operating on sorted sets */
  990. 'zadd' => '\Predis\Commands\ZSetAdd',
  991. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  992. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  993. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  994. 'zrem' => '\Predis\Commands\ZSetRemove',
  995. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  996. 'zrange' => '\Predis\Commands\ZSetRange',
  997. 'zsetRange' => '\Predis\Commands\ZSetRange',
  998. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  999. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1000. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1001. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1002. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1003. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1004. 'zscore' => '\Predis\Commands\ZSetScore',
  1005. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1006. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1007. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1008. /* persistence control commands */
  1009. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1010. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1011. ));
  1012. }
  1013. }
  1014. class RedisServer_vNext extends RedisServer_v1_2 {
  1015. public function getVersion() { return '1.3'; }
  1016. public function getSupportedCommands() {
  1017. return array_merge(parent::getSupportedCommands(), array(
  1018. /* miscellaneous commands */
  1019. 'multi' => '\Predis\Commands\Multi',
  1020. 'exec' => '\Predis\Commands\Exec',
  1021. 'discard' => '\Predis\Commands\Discard',
  1022. /* commands operating on string values */
  1023. 'append' => '\Predis\Commands\Append',
  1024. 'substr' => '\Predis\Commands\Substr',
  1025. /* commands operating on lists */
  1026. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1027. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1028. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1029. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1030. /* commands operating on sorted sets */
  1031. 'zunion' => '\Predis\Commands\ZSetUnion',
  1032. 'zsetUnion' => '\Predis\Commands\ZSetUnion',
  1033. 'zinter' => '\Predis\Commands\ZSetIntersection',
  1034. 'zsetIntersection' => '\Predis\Commands\ZSetIntersection',
  1035. 'zcount' => '\Predis\Commands\ZSetCount',
  1036. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1037. 'zrank' => '\Predis\Commands\ZSetRank',
  1038. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1039. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1040. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1041. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1042. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1043. /* commands operating on hashes */
  1044. 'hset' => '\Predis\Commands\HashSet',
  1045. 'hashSet' => '\Predis\Commands\HashSet',
  1046. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1047. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1048. 'hget' => '\Predis\Commands\HashGet',
  1049. 'hashGet' => '\Predis\Commands\HashGet',
  1050. 'hdel' => '\Predis\Commands\HashDelete',
  1051. 'hashDelete' => '\Predis\Commands\HashDelete',
  1052. 'hexists' => '\Predis\Commands\HashExists',
  1053. 'hashExists' => '\Predis\Commands\HashExists',
  1054. 'hlen' => '\Predis\Commands\HashLength',
  1055. 'hashLength' => '\Predis\Commands\HashLength',
  1056. 'hkeys' => '\Predis\Commands\HashKeys',
  1057. 'hashKeys' => '\Predis\Commands\HashKeys',
  1058. 'hvals' => '\Predis\Commands\HashValues',
  1059. 'hashValues' => '\Predis\Commands\HashValues',
  1060. 'hgetall' => '\Predis\Commands\HashGetAll',
  1061. 'hashKeysValues' => '\Predis\Commands\HashGetAll',
  1062. /* remote server control commands */
  1063. 'config' => '\Predis\Commands\Config',
  1064. 'configuration' => '\Predis\Commands\Config',
  1065. ));
  1066. }
  1067. }
  1068. /* ------------------------------------------------------------------------- */
  1069. namespace Predis\Utilities;
  1070. class HashRing {
  1071. const DEFAULT_REPLICAS = 128;
  1072. const DEFAULT_WEIGHT = 100;
  1073. private $_nodes, $_ring, $_ringKeys, $_replicas;
  1074. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1075. $this->_replicas = $replicas;
  1076. $this->_nodes = array();
  1077. }
  1078. public function add($node, $weight = self::DEFAULT_WEIGHT) {
  1079. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1080. // last wins, thus the order in which nodes are added is significant.
  1081. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight);
  1082. $this->reset();
  1083. }
  1084. public function remove($node) {
  1085. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1086. // scratch, in order to reassign possible hashes with collisions to the
  1087. // right node according to the order in which they were added in the
  1088. // first place.
  1089. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1090. if ($this->_nodes[$i]['object'] === $node) {
  1091. array_splice($this->_nodes, $i, 1);
  1092. $this->reset();
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. private function reset() {
  1098. unset($this->_ring);
  1099. unset($this->_ringKeys);
  1100. }
  1101. private function isInitialized() {
  1102. return isset($this->_ringKeys);
  1103. }
  1104. private function computeTotalWeight() {
  1105. // TODO: array_reduce + lambda for PHP 5.3
  1106. $totalWeight = 0;
  1107. foreach ($this->_nodes as $node) {
  1108. $totalWeight += $node['weight'];
  1109. }
  1110. return $totalWeight;
  1111. }
  1112. private function initialize() {
  1113. if ($this->isInitialized()) {
  1114. return;
  1115. }
  1116. if (count($this->_nodes) === 0) {
  1117. throw new \LogicException('Cannot initialize empty hashring');
  1118. }
  1119. $this->_ring = array();
  1120. $totalWeight = $this->computeTotalWeight();
  1121. $nodesCount = count($this->_nodes);
  1122. foreach ($this->_nodes as $node) {
  1123. $nodeObject = $node['object'];
  1124. $nodeHash = (string) $nodeObject;
  1125. $weightRatio = $node['weight'] / $totalWeight;
  1126. $replicas = (int) round($weightRatio * $nodesCount * $this->_replicas);
  1127. for ($i = 0; $i < $replicas; $i++) {
  1128. $key = crc32($nodeHash . ':' . $i);
  1129. $this->_ring[$key] = $nodeObject;
  1130. }
  1131. }
  1132. ksort($this->_ring, SORT_NUMERIC);
  1133. $this->_ringKeys = array_keys($this->_ring);
  1134. }
  1135. public function get($key) {
  1136. return $this->_ring[$this->getNodeKey($key)];
  1137. }
  1138. private function getNodeKey($key) {
  1139. // NOTE: binary search for the last item in _ringkeys with a value
  1140. // less or equal to the key. If no such item exists, return the
  1141. // last item.
  1142. $this->initialize();
  1143. $ringKeys = $this->_ringKeys;
  1144. $upper = count($ringKeys) - 1;
  1145. $lower = 0;
  1146. while ($lower <= $upper) {
  1147. $index = ($lower + $upper) >> 1;
  1148. $item = $ringKeys[$index];
  1149. if ($item > $key) {
  1150. $upper = $index - 1;
  1151. }
  1152. else if ($item < $key) {
  1153. $lower = $index + 1;
  1154. }
  1155. else {
  1156. return $item;
  1157. }
  1158. }
  1159. return $ringKeys[$upper >= 0 ? $upper : count($ringKeys) - 1];
  1160. }
  1161. }
  1162. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1163. protected $_position, $_current, $_replySize;
  1164. public function rewind() {
  1165. // NOOP
  1166. }
  1167. public function current() {
  1168. return $this->_current;
  1169. }
  1170. public function key() {
  1171. return $this->_position;
  1172. }
  1173. public function next() {
  1174. if (++$this->_position < $this->_replySize) {
  1175. $this->_current = $this->getValue();
  1176. }
  1177. return $this->_position;
  1178. }
  1179. public function valid() {
  1180. return $this->_position < $this->_replySize;
  1181. }
  1182. public function count() {
  1183. // NOTE: use count if you want to get the size of the current multi-bulk
  1184. // response without using iterator_count (which actually consumes
  1185. // our iterator to calculate the size, and we cannot perform a rewind)
  1186. return $this->_replySize;
  1187. }
  1188. protected abstract function getValue();
  1189. }
  1190. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1191. private $_connection;
  1192. public function __construct(\Predis\Connection $connection, $size) {
  1193. $this->_connection = $connection;
  1194. $this->_reader = $connection->getResponseReader();
  1195. $this->_position = 0;
  1196. $this->_current = $size > 0 ? $this->getValue() : null;
  1197. $this->_replySize = $size;
  1198. }
  1199. public function __destruct() {
  1200. // when the iterator is garbage-collected (e.g. it goes out of the
  1201. // scope of a foreach) but it has not reached its end, we must sync
  1202. // the client with the queued elements that have not been read from
  1203. // the connection with the server.
  1204. $this->sync();
  1205. }
  1206. public function sync() {
  1207. while ($this->valid()) {
  1208. $this->next();
  1209. }
  1210. }
  1211. protected function getValue() {
  1212. return $this->_reader->read($this->_connection);
  1213. }
  1214. }
  1215. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1216. private $_iterator;
  1217. public function __construct(MultiBulkResponseIterator $iterator) {
  1218. $virtualSize = count($iterator) / 2;
  1219. $this->_iterator = $iterator;
  1220. $this->_position = 0;
  1221. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1222. $this->_replySize = $virtualSize;
  1223. }
  1224. public function __destruct() {
  1225. $this->_iterator->sync();
  1226. }
  1227. protected function getValue() {
  1228. $k = $this->_iterator->current();
  1229. $this->_iterator->next();
  1230. $v = $this->_iterator->current();
  1231. $this->_iterator->next();
  1232. return array($k, $v);
  1233. }
  1234. }
  1235. /* ------------------------------------------------------------------------- */
  1236. namespace Predis\Commands;
  1237. /* miscellaneous commands */
  1238. class Ping extends \Predis\InlineCommand {
  1239. public function canBeHashed() { return false; }
  1240. public function getCommandId() { return 'PING'; }
  1241. public function parseResponse($data) {
  1242. return $data === 'PONG' ? true : false;
  1243. }
  1244. }
  1245. class DoEcho extends \Predis\BulkCommand {
  1246. public function canBeHashed() { return false; }
  1247. public function getCommandId() { return 'ECHO'; }
  1248. }
  1249. class Auth extends \Predis\InlineCommand {
  1250. public function canBeHashed() { return false; }
  1251. public function getCommandId() { return 'AUTH'; }
  1252. }
  1253. /* connection handling */
  1254. class Quit extends \Predis\InlineCommand {
  1255. public function canBeHashed() { return false; }
  1256. public function getCommandId() { return 'QUIT'; }
  1257. public function closesConnection() { return true; }
  1258. }
  1259. /* commands operating on string values */
  1260. class Set extends \Predis\BulkCommand {
  1261. public function getCommandId() { return 'SET'; }
  1262. }
  1263. class SetPreserve extends \Predis\BulkCommand {
  1264. public function getCommandId() { return 'SETNX'; }
  1265. public function parseResponse($data) { return (bool) $data; }
  1266. }
  1267. class SetMultiple extends \Predis\MultiBulkCommand {
  1268. public function canBeHashed() { return false; }
  1269. public function getCommandId() { return 'MSET'; }
  1270. }
  1271. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1272. public function canBeHashed() { return false; }
  1273. public function getCommandId() { return 'MSETNX'; }
  1274. public function parseResponse($data) { return (bool) $data; }
  1275. }
  1276. class Get extends \Predis\InlineCommand {
  1277. public function getCommandId() { return 'GET'; }
  1278. }
  1279. class GetMultiple extends \Predis\InlineCommand {
  1280. public function canBeHashed() { return false; }
  1281. public function getCommandId() { return 'MGET'; }
  1282. }
  1283. class GetSet extends \Predis\BulkCommand {
  1284. public function getCommandId() { return 'GETSET'; }
  1285. }
  1286. class Increment extends \Predis\InlineCommand {
  1287. public function getCommandId() { return 'INCR'; }
  1288. }
  1289. class IncrementBy extends \Predis\InlineCommand {
  1290. public function getCommandId() { return 'INCRBY'; }
  1291. }
  1292. class Decrement extends \Predis\InlineCommand {
  1293. public function getCommandId() { return 'DECR'; }
  1294. }
  1295. class DecrementBy extends \Predis\InlineCommand {
  1296. public function getCommandId() { return 'DECRBY'; }
  1297. }
  1298. class Exists extends \Predis\InlineCommand {
  1299. public function getCommandId() { return 'EXISTS'; }
  1300. public function parseResponse($data) { return (bool) $data; }
  1301. }
  1302. class Delete extends \Predis\InlineCommand {
  1303. public function getCommandId() { return 'DEL'; }
  1304. public function parseResponse($data) { return (bool) $data; }
  1305. }
  1306. class Type extends \Predis\InlineCommand {
  1307. public function getCommandId() { return 'TYPE'; }
  1308. }
  1309. class Append extends \Predis\BulkCommand {
  1310. public function getCommandId() { return 'APPEND'; }
  1311. }
  1312. class Substr extends \Predis\InlineCommand {
  1313. public function getCommandId() { return 'SUBSTR'; }
  1314. }
  1315. /* commands operating on the key space */
  1316. class Keys extends \Predis\InlineCommand {
  1317. public function canBeHashed() { return false; }
  1318. public function getCommandId() { return 'KEYS'; }
  1319. public function parseResponse($data) {
  1320. // TODO: is this behaviour correct?
  1321. if (is_array($data) || $data instanceof \Iterator) {
  1322. return $data;
  1323. }
  1324. return strlen($data) > 0 ? explode(' ', $data) : array();
  1325. }
  1326. }
  1327. class RandomKey extends \Predis\InlineCommand {
  1328. public function canBeHashed() { return false; }
  1329. public function getCommandId() { return 'RANDOMKEY'; }
  1330. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1331. }
  1332. class Rename extends \Predis\InlineCommand {
  1333. public function canBeHashed() { return false; }
  1334. public function getCommandId() { return 'RENAME'; }
  1335. }
  1336. class RenamePreserve extends \Predis\InlineCommand {
  1337. public function canBeHashed() { return false; }
  1338. public function getCommandId() { return 'RENAMENX'; }
  1339. public function parseResponse($data) { return (bool) $data; }
  1340. }
  1341. class Expire extends \Predis\InlineCommand {
  1342. public function getCommandId() { return 'EXPIRE'; }
  1343. public function parseResponse($data) { return (bool) $data; }
  1344. }
  1345. class ExpireAt extends \Predis\InlineCommand {
  1346. public function getCommandId() { return 'EXPIREAT'; }
  1347. public function parseResponse($data) { return (bool) $data; }
  1348. }
  1349. class DatabaseSize extends \Predis\InlineCommand {
  1350. public function canBeHashed() { return false; }
  1351. public function getCommandId() { return 'DBSIZE'; }
  1352. }
  1353. class TimeToLive extends \Predis\InlineCommand {
  1354. public function getCommandId() { return 'TTL'; }
  1355. }
  1356. /* commands operating on lists */
  1357. class ListPushTail extends \Predis\BulkCommand {
  1358. public function getCommandId() { return 'RPUSH'; }
  1359. }
  1360. class ListPushHead extends \Predis\BulkCommand {
  1361. public function getCommandId() { return 'LPUSH'; }
  1362. }
  1363. class ListLength extends \Predis\InlineCommand {
  1364. public function getCommandId() { return 'LLEN'; }
  1365. }
  1366. class ListRange extends \Predis\InlineCommand {
  1367. public function getCommandId() { return 'LRANGE'; }
  1368. }
  1369. class ListTrim extends \Predis\InlineCommand {
  1370. public function getCommandId() { return 'LTRIM'; }
  1371. }
  1372. class ListIndex extends \Predis\InlineCommand {
  1373. public function getCommandId() { return 'LINDEX'; }
  1374. }
  1375. class ListSet extends \Predis\BulkCommand {
  1376. public function getCommandId() { return 'LSET'; }
  1377. }
  1378. class ListRemove extends \Predis\BulkCommand {
  1379. public function getCommandId() { return 'LREM'; }
  1380. }
  1381. class ListPopLastPushHead extends \Predis\InlineCommand {
  1382. public function getCommandId() { return 'RPOPLPUSH'; }
  1383. }
  1384. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1385. public function getCommandId() { return 'RPOPLPUSH'; }
  1386. }
  1387. class ListPopFirst extends \Predis\InlineCommand {
  1388. public function getCommandId() { return 'LPOP'; }
  1389. }
  1390. class ListPopLast extends \Predis\InlineCommand {
  1391. public function getCommandId() { return 'RPOP'; }
  1392. }
  1393. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1394. public function getCommandId() { return 'BLPOP'; }
  1395. }
  1396. class ListPopLastBlocking extends \Predis\InlineCommand {
  1397. public function getCommandId() { return 'BRPOP'; }
  1398. }
  1399. /* commands operating on sets */
  1400. class SetAdd extends \Predis\BulkCommand {
  1401. public function getCommandId() { return 'SADD'; }
  1402. public function parseResponse($data) { return (bool) $data; }
  1403. }
  1404. class SetRemove extends \Predis\BulkCommand {
  1405. public function getCommandId() { return 'SREM'; }
  1406. public function parseResponse($data) { return (bool) $data; }
  1407. }
  1408. class SetPop extends \Predis\InlineCommand {
  1409. public function getCommandId() { return 'SPOP'; }
  1410. }
  1411. class SetMove extends \Predis\BulkCommand {
  1412. public function canBeHashed() { return false; }
  1413. public function getCommandId() { return 'SMOVE'; }
  1414. public function parseResponse($data) { return (bool) $data; }
  1415. }
  1416. class SetCardinality extends \Predis\InlineCommand {
  1417. public function getCommandId() { return 'SCARD'; }
  1418. }
  1419. class SetIsMember extends \Predis\BulkCommand {
  1420. public function getCommandId() { return 'SISMEMBER'; }
  1421. public function parseResponse($data) { return (bool) $data; }
  1422. }
  1423. class SetIntersection extends \Predis\InlineCommand {
  1424. public function getCommandId() { return 'SINTER'; }
  1425. }
  1426. class SetIntersectionStore extends \Predis\InlineCommand {
  1427. public function getCommandId() { return 'SINTERSTORE'; }
  1428. }
  1429. class SetUnion extends \Predis\InlineCommand {
  1430. public function getCommandId() { return 'SUNION'; }
  1431. }
  1432. class SetUnionStore extends \Predis\InlineCommand {
  1433. public function getCommandId() { return 'SUNIONSTORE'; }
  1434. }
  1435. class SetDifference extends \Predis\InlineCommand {
  1436. public function getCommandId() { return 'SDIFF'; }
  1437. }
  1438. class SetDifferenceStore extends \Predis\InlineCommand {
  1439. public function getCommandId() { return 'SDIFFSTORE'; }
  1440. }
  1441. class SetMembers extends \Predis\InlineCommand {
  1442. public function getCommandId() { return 'SMEMBERS'; }
  1443. }
  1444. class SetRandomMember extends \Predis\InlineCommand {
  1445. public function getCommandId() { return 'SRANDMEMBER'; }
  1446. }
  1447. /* commands operating on sorted sets */
  1448. class ZSetAdd extends \Predis\BulkCommand {
  1449. public function getCommandId() { return 'ZADD'; }
  1450. public function parseResponse($data) { return (bool) $data; }
  1451. }
  1452. class ZSetIncrementBy extends \Predis\BulkCommand {
  1453. public function getCommandId() { return 'ZINCRBY'; }
  1454. }
  1455. class ZSetRemove extends \Predis\BulkCommand {
  1456. public function getCommandId() { return 'ZREM'; }
  1457. public function parseResponse($data) { return (bool) $data; }
  1458. }
  1459. class ZSetUnion extends \Predis\InlineCommand {
  1460. public function getCommandId() { return 'ZUNION'; }
  1461. }
  1462. class ZSetIntersection extends \Predis\InlineCommand {
  1463. public function getCommandId() { return 'ZINTER'; }
  1464. }
  1465. class ZSetRange extends \Predis\InlineCommand {
  1466. public function getCommandId() { return 'ZRANGE'; }
  1467. public function parseResponse($data) {
  1468. $arguments = $this->getArguments();
  1469. if (count($arguments) === 4) {
  1470. if (strtolower($arguments[3]) === 'withscores') {
  1471. if ($data instanceof \Iterator) {
  1472. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1473. }
  1474. $result = array();
  1475. for ($i = 0; $i < count($data); $i++) {
  1476. $result[] = array($data[$i], $data[++$i]);
  1477. }
  1478. return $result;
  1479. }
  1480. }
  1481. return $data;
  1482. }
  1483. }
  1484. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1485. public function getCommandId() { return 'ZREVRANGE'; }
  1486. }
  1487. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1488. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1489. }
  1490. class ZSetCount extends \Predis\InlineCommand {
  1491. public function getCommandId() { return 'ZCOUNT'; }
  1492. }
  1493. class ZSetCardinality extends \Predis\InlineCommand {
  1494. public function getCommandId() { return 'ZCARD'; }
  1495. }
  1496. class ZSetScore extends \Predis\BulkCommand {
  1497. public function getCommandId() { return 'ZSCORE'; }
  1498. }
  1499. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1500. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1501. }
  1502. class ZSetRank extends \Predis\BulkCommand {
  1503. public function getCommandId() { return 'ZRANK'; }
  1504. }
  1505. class ZSetReverseRank extends \Predis\BulkCommand {
  1506. public function getCommandId() { return 'ZREVRANK'; }
  1507. }
  1508. class ZSetRemoveRangeByRank extends \Predis\InlineCommand {
  1509. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1510. }
  1511. /* commands operating on hashes */
  1512. class HashSet extends \Predis\MultiBulkCommand {
  1513. public function getCommandId() { return 'HSET'; }
  1514. }
  1515. class HashIncrementBy extends \Predis\InlineCommand {
  1516. public function getCommandId() { return 'HINCRBY'; }
  1517. }
  1518. class HashGet extends \Predis\BulkCommand {
  1519. public function getCommandId() { return 'HGET'; }
  1520. }
  1521. class HashDelete extends \Predis\BulkCommand {
  1522. public function getCommandId() { return 'HDEL'; }
  1523. }
  1524. class HashExists extends \Predis\BulkCommand {
  1525. public function getCommandId() { return 'HEXISTS'; }
  1526. }
  1527. class HashLength extends \Predis\InlineCommand {
  1528. public function getCommandId() { return 'HLEN'; }
  1529. }
  1530. class HashKeys extends \Predis\InlineCommand {
  1531. public function getCommandId() { return 'HKEYS'; }
  1532. }
  1533. class HashValues extends \Predis\InlineCommand {
  1534. public function getCommandId() { return 'HVALS'; }
  1535. }
  1536. class HashGetAll extends \Predis\InlineCommand {
  1537. public function getCommandId() { return 'HGETALL'; }
  1538. }
  1539. /* multiple databases handling commands */
  1540. class SelectDatabase extends \Predis\InlineCommand {
  1541. public function canBeHashed() { return false; }
  1542. public function getCommandId() { return 'SELECT'; }
  1543. }
  1544. class MoveKey extends \Predis\InlineCommand {
  1545. public function canBeHashed() { return false; }
  1546. public function getCommandId() { return 'MOVE'; }
  1547. public function parseResponse($data) { return (bool) $data; }
  1548. }
  1549. class FlushDatabase extends \Predis\InlineCommand {
  1550. public function canBeHashed() { return false; }
  1551. public function getCommandId() { return 'FLUSHDB'; }
  1552. }
  1553. class FlushAll extends \Predis\InlineCommand {
  1554. public function canBeHashed() { return false; }
  1555. public function getCommandId() { return 'FLUSHALL'; }
  1556. }
  1557. /* sorting */
  1558. class Sort extends \Predis\InlineCommand {
  1559. public function getCommandId() { return 'SORT'; }
  1560. public function filterArguments(Array $arguments) {
  1561. if (count($arguments) === 1) {
  1562. return $arguments;
  1563. }
  1564. // TODO: add more parameters checks
  1565. $query = array($arguments[0]);
  1566. $sortParams = $arguments[1];
  1567. if (isset($sortParams['by'])) {
  1568. $query[] = 'BY ' . $sortParams['by'];
  1569. }
  1570. if (isset($sortParams['get'])) {
  1571. $getargs = $sortParams['get'];
  1572. if (is_array($getargs)) {
  1573. foreach ($getargs as $getarg) {
  1574. $query[] = 'GET ' . $getarg;
  1575. }
  1576. }
  1577. else {
  1578. $query[] = 'GET ' . $getargs;
  1579. }
  1580. }
  1581. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1582. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1583. }
  1584. if (isset($sortParams['sort'])) {
  1585. $query[] = strtoupper($sortParams['sort']);
  1586. }
  1587. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1588. $query[] = 'ALPHA';
  1589. }
  1590. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1591. $query[] = 'STORE ' . $sortParams['store'];
  1592. }
  1593. return $query;
  1594. }
  1595. }
  1596. /* persistence control commands */
  1597. class Save extends \Predis\InlineCommand {
  1598. public function canBeHashed() { return false; }
  1599. public function getCommandId() { return 'SAVE'; }
  1600. }
  1601. class BackgroundSave extends \Predis\InlineCommand {
  1602. public function canBeHashed() { return false; }
  1603. public function getCommandId() { return 'BGSAVE'; }
  1604. public function parseResponse($data) {
  1605. if ($data == 'Background saving started') {
  1606. return true;
  1607. }
  1608. return $data;
  1609. }
  1610. }
  1611. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1612. public function canBeHashed() { return false; }
  1613. public function getCommandId() { return 'BGREWRITEAOF'; }
  1614. public function parseResponse($data) {
  1615. return $data == 'Background append only file rewriting started';
  1616. }
  1617. }
  1618. class LastSave extends \Predis\InlineCommand {
  1619. public function canBeHashed() { return false; }
  1620. public function getCommandId() { return 'LASTSAVE'; }
  1621. }
  1622. class Shutdown extends \Predis\InlineCommand {
  1623. public function canBeHashed() { return false; }
  1624. public function getCommandId() { return 'SHUTDOWN'; }
  1625. public function closesConnection() { return true; }
  1626. }
  1627. /* remote server control commands */
  1628. class Info extends \Predis\InlineCommand {
  1629. public function canBeHashed() { return false; }
  1630. public function getCommandId() { return 'INFO'; }
  1631. public function parseResponse($data) {
  1632. $info = array();
  1633. $infoLines = explode("\r\n", $data, -1);
  1634. foreach ($infoLines as $row) {
  1635. list($k, $v) = explode(':', $row);
  1636. if (!preg_match('/^db\d+$/', $k)) {
  1637. $info[$k] = $v;
  1638. }
  1639. else {
  1640. $db = array();
  1641. foreach (explode(',', $v) as $dbvar) {
  1642. list($dbvk, $dbvv) = explode('=', $dbvar);
  1643. $db[trim($dbvk)] = $dbvv;
  1644. }
  1645. $info[$k] = $db;
  1646. }
  1647. }
  1648. return $info;
  1649. }
  1650. }
  1651. class SlaveOf extends \Predis\InlineCommand {
  1652. public function canBeHashed() { return false; }
  1653. public function getCommandId() { return 'SLAVEOF'; }
  1654. public function filterArguments(Array $arguments) {
  1655. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1656. }
  1657. }
  1658. class Config extends \Predis\BulkCommand {
  1659. public function canBeHashed() { return false; }
  1660. public function getCommandId() { return 'CONFIG'; }
  1661. }
  1662. class Multi extends \Predis\InlineCommand {
  1663. public function canBeHashed() { return false; }
  1664. public function getCommandId() { return 'MULTI'; }
  1665. }
  1666. class Exec extends \Predis\InlineCommand {
  1667. public function canBeHashed() { return false; }
  1668. public function getCommandId() { return 'EXEC'; }
  1669. }
  1670. class Discard extends \Predis\InlineCommand {
  1671. public function canBeHashed() { return false; }
  1672. public function getCommandId() { return 'DISCARD'; }
  1673. }
  1674. ?>