Predis.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  1. <?php
  2. class PredisException extends Exception { }
  3. class Predis_ClientException extends PredisException { }
  4. class Predis_ServerException extends PredisException { }
  5. class Predis_MalformedServerResponse extends Predis_ServerException { }
  6. /* ------------------------------------------------------------------------- */
  7. class Predis_Client {
  8. private $_connection, $_serverProfile;
  9. public function __construct($parameters = null, Predis_RedisServerProfile $serverProfile = null) {
  10. $this->setProfile(
  11. $serverProfile === null
  12. ? Predis_RedisServerProfile::getDefault()
  13. : $serverProfile
  14. );
  15. $this->setupConnection($parameters);
  16. }
  17. public function __destruct() {
  18. $this->_connection->disconnect();
  19. }
  20. public static function create(/* arguments */) {
  21. $argv = func_get_args();
  22. $argc = func_num_args();
  23. $serverProfile = null;
  24. $lastArg = $argv[$argc-1];
  25. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, 'Predis_RedisServerProfile')) {
  26. $serverProfile = array_pop($argv);
  27. $argc--;
  28. }
  29. if ($argc === 0) {
  30. throw new Predis_ClientException('Missing connection parameters');
  31. }
  32. return new Predis_Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  33. }
  34. private function setupConnection($parameters) {
  35. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  36. throw new Predis_ClientException('Invalid parameters type (array or string expected)');
  37. }
  38. if (is_array($parameters) && isset($parameters[0])) {
  39. $cluster = new Predis_ConnectionCluster();
  40. foreach ($parameters as $shardParams) {
  41. $cluster->add($this->createConnection($shardParams));
  42. }
  43. $this->setConnection($cluster);
  44. }
  45. else {
  46. $this->setConnection($this->createConnection($parameters));
  47. }
  48. }
  49. private function createConnection($parameters) {
  50. $params = new Predis_ConnectionParameters($parameters);
  51. $connection = new Predis_Connection($params);
  52. if ($params->password !== null) {
  53. $connection->pushInitCommand($this->createCommand(
  54. 'auth', array($params->password)
  55. ));
  56. }
  57. if ($params->database !== null) {
  58. $connection->pushInitCommand($this->createCommand(
  59. 'select', array($params->database)
  60. ));
  61. }
  62. return $connection;
  63. }
  64. private function setConnection(Predis_IConnection $connection) {
  65. $this->_connection = $connection;
  66. }
  67. public function setProfile(Predis_RedisServerProfile $serverProfile) {
  68. $this->_serverProfile = $serverProfile;
  69. }
  70. public function getProfile() {
  71. return $this->_serverProfile;
  72. }
  73. public function connect() {
  74. $this->_connection->connect();
  75. }
  76. public function disconnect() {
  77. $this->_connection->disconnect();
  78. }
  79. public function isConnected() {
  80. return $this->_connection->isConnected();
  81. }
  82. public function getConnection() {
  83. return $this->_connection;
  84. }
  85. public function __call($method, $arguments) {
  86. $command = $this->_serverProfile->createCommand($method, $arguments);
  87. return $this->executeCommand($command);
  88. }
  89. public function createCommand($method, $arguments = array()) {
  90. return $this->_serverProfile->createCommand($method, $arguments);
  91. }
  92. private function executeCommandInternal(Predis_IConnection $connection, Predis_Command $command) {
  93. $connection->writeCommand($command);
  94. if ($command->closesConnection()) {
  95. return $connection->disconnect();
  96. }
  97. return $connection->readResponse($command);
  98. }
  99. public function executeCommand(Predis_Command $command) {
  100. return self::executeCommandInternal($this->_connection, $command);
  101. }
  102. public function executeCommandOnShards(Predis_Command $command) {
  103. $replies = array();
  104. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  105. foreach($this->_connection as $connection) {
  106. $replies[] = self::executeCommandInternal($connection, $command);
  107. }
  108. }
  109. else {
  110. $replies[] = self::executeCommandInternal($this->_connection, $command);
  111. }
  112. return $replies;
  113. }
  114. public function rawCommand($rawCommandData, $closesConnection = false) {
  115. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  116. throw new Predis_ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  117. }
  118. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  119. }
  120. public function pipeline($pipelineBlock = null) {
  121. $pipeline = new Predis_CommandPipeline($this);
  122. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  123. }
  124. public function multiExec($multiExecBlock = null) {
  125. $multiExec = new Predis_MultiExecBlock($this);
  126. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  127. }
  128. }
  129. /* ------------------------------------------------------------------------- */
  130. abstract class Predis_Command {
  131. private $_arguments, $_hash;
  132. public abstract function getCommandId();
  133. public abstract function serializeRequest($command, $arguments);
  134. public function canBeHashed() {
  135. return true;
  136. }
  137. public function getHash() {
  138. if (isset($this->_hash)) {
  139. return $this->_hash;
  140. }
  141. else {
  142. if (isset($this->_arguments[0])) {
  143. $key = $this->_arguments[0];
  144. $start = strpos($key, '{');
  145. $end = strpos($key, '}');
  146. if ($start !== false && $end !== false) {
  147. $key = substr($key, ++$start, $end - $start);
  148. }
  149. $this->_hash = crc32($key);
  150. return $this->_hash;
  151. }
  152. }
  153. return null;
  154. }
  155. public function closesConnection() {
  156. return false;
  157. }
  158. protected function filterArguments(Array $arguments) {
  159. return $arguments;
  160. }
  161. public function setArguments(/* arguments */) {
  162. $this->_arguments = $this->filterArguments(func_get_args());
  163. }
  164. public function setArgumentsArray(Array $arguments) {
  165. $this->_arguments = $this->filterArguments($arguments);
  166. }
  167. protected function getArguments() {
  168. return isset($this->_arguments) ? $this->_arguments : array();
  169. }
  170. public function getArgument($index = 0) {
  171. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  172. }
  173. public function parseResponse($data) {
  174. return $data;
  175. }
  176. public final function invoke() {
  177. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  178. }
  179. }
  180. abstract class Predis_InlineCommand extends Predis_Command {
  181. public function serializeRequest($command, $arguments) {
  182. if (isset($arguments[0]) && is_array($arguments[0])) {
  183. $arguments[0] = implode($arguments[0], ' ');
  184. }
  185. return $command . ' ' . implode($arguments, ' ') . Predis_Response::NEWLINE;
  186. }
  187. }
  188. abstract class Predis_BulkCommand extends Predis_Command {
  189. public function serializeRequest($command, $arguments) {
  190. $data = array_pop($arguments);
  191. if (is_array($data)) {
  192. $data = implode($data, ' ');
  193. }
  194. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  195. Predis_Response::NEWLINE . $data . Predis_Response::NEWLINE;
  196. }
  197. }
  198. abstract class Predis_MultiBulkCommand extends Predis_Command {
  199. public function serializeRequest($command, $arguments) {
  200. $buffer = array();
  201. $cmd_args = null;
  202. if (count($arguments) === 1 && is_array($arguments[0])) {
  203. $cmd_args = array();
  204. foreach ($arguments[0] as $k => $v) {
  205. $cmd_args[] = $k;
  206. $cmd_args[] = $v;
  207. }
  208. }
  209. else {
  210. $cmd_args = $arguments;
  211. }
  212. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Predis_Response::NEWLINE;
  213. $buffer[] = '$' . strlen($command) . Predis_Response::NEWLINE . $command . Predis_Response::NEWLINE;
  214. foreach ($cmd_args as $argument) {
  215. $buffer[] = '$' . strlen($argument) . Predis_Response::NEWLINE . $argument . Predis_Response::NEWLINE;
  216. }
  217. return implode('', $buffer);
  218. }
  219. }
  220. /* ------------------------------------------------------------------------- */
  221. class Predis_Response {
  222. const NEWLINE = "\r\n";
  223. const OK = 'OK';
  224. const ERROR = 'ERR';
  225. const QUEUED = 'QUEUED';
  226. const NULL = 'nil';
  227. private static $_prefixHandlers;
  228. private static function initializePrefixHandlers() {
  229. return array(
  230. // status
  231. '+' => array('Predis_Response', 'handleStatus'),
  232. // error
  233. '-' => array('Predis_Response', 'handleError'),
  234. // bulk
  235. '$' => array('Predis_Response', 'handleBulk'),
  236. // multibulk
  237. '*' => array('Predis_Response', 'handleMultiBulk'),
  238. // integer
  239. ':' => array('Predis_Response', 'handleInteger')
  240. );
  241. }
  242. public static function handleStatus($socket, $prefix, $status) {
  243. if ($status === Predis_Response::OK) {
  244. return true;
  245. }
  246. else if ($status === Predis_Response::QUEUED) {
  247. return new Predis_ResponseQueued();
  248. }
  249. return $status;
  250. }
  251. public static function handleError($socket, $prefix, $errorMessage) {
  252. throw new Predis_ServerException(substr($errorMessage, 4));
  253. }
  254. public static function handleBulk($socket, $prefix, $dataLength) {
  255. if (!is_numeric($dataLength)) {
  256. throw new Predis_ClientException("Cannot parse '$dataLength' as data length");
  257. }
  258. if ($dataLength > 0) {
  259. $value = stream_get_contents($socket, $dataLength);
  260. if ($value === false) {
  261. throw new Predis_ClientException('An error has occurred while reading from the network stream');
  262. }
  263. fread($socket, 2);
  264. return $value;
  265. }
  266. else if ($dataLength == 0) {
  267. fread($socket, 2);
  268. return '';
  269. }
  270. return null;
  271. }
  272. public static function handleMultiBulk($socket, $prefix, $rawLength) {
  273. if (!is_numeric($rawLength)) {
  274. throw new Predis_ClientException("Cannot parse '$rawLength' as data length");
  275. }
  276. $listLength = (int) $rawLength;
  277. if ($listLength === -1) {
  278. return null;
  279. }
  280. $list = array();
  281. if ($listLength > 0) {
  282. for ($i = 0; $i < $listLength; $i++) {
  283. $list[] = Predis_Response::read($socket);
  284. }
  285. }
  286. return $list;
  287. }
  288. public static function handleInteger($socket, $prefix, $number) {
  289. if (is_numeric($number)) {
  290. return (int) $number;
  291. }
  292. else {
  293. if ($number !== Response::NULL) {
  294. throw new Predis_ClientException("Cannot parse '$number' as numeric response");
  295. }
  296. return null;
  297. }
  298. }
  299. public static function read($socket) {
  300. $header = fgets($socket);
  301. if ($header === false) {
  302. throw new Predis_ClientException('An error has occurred while reading from the network stream');
  303. }
  304. $prefix = $header[0];
  305. $payload = substr($header, 1, -2);
  306. if (!isset(self::$_prefixHandlers)) {
  307. self::$_prefixHandlers = self::initializePrefixHandlers();
  308. }
  309. if (!isset(self::$_prefixHandlers[$prefix])) {
  310. throw new Predis_MalformedServerResponse("Unknown prefix '$prefix'");
  311. }
  312. $handler = self::$_prefixHandlers[$prefix];
  313. return call_user_func($handler, $socket, $prefix, $payload);
  314. }
  315. }
  316. class Predis_ResponseQueued {
  317. public $queued = true;
  318. public function __toString() {
  319. return Predis_Response::QUEUED;
  320. }
  321. }
  322. class Predis_CommandPipeline {
  323. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  324. public function __construct(Predis_Client $redisClient) {
  325. $this->_redisClient = $redisClient;
  326. $this->_pipelineBuffer = array();
  327. $this->_returnValues = array();
  328. }
  329. public function __call($method, $arguments) {
  330. $command = $this->_redisClient->createCommand($method, $arguments);
  331. $this->recordCommand($command);
  332. }
  333. private function recordCommand(Predis_Command $command) {
  334. $this->_pipelineBuffer[] = $command;
  335. }
  336. private function getRecordedCommands() {
  337. return $this->_pipelineBuffer;
  338. }
  339. public function flushPipeline() {
  340. $sizeofPipe = count($this->_pipelineBuffer);
  341. if ($sizeofPipe === 0) {
  342. return;
  343. }
  344. $connection = $this->_redisClient->getConnection();
  345. $commands = &$this->_pipelineBuffer;
  346. foreach ($commands as $command) {
  347. $connection->writeCommand($command);
  348. }
  349. for ($i = 0; $i < $sizeofPipe; $i++) {
  350. $this->_returnValues[] = $connection->readResponse($commands[$i]);
  351. unset($commands[$i]);
  352. }
  353. }
  354. private function setRunning($bool) {
  355. if ($bool == true && $this->_running == true) {
  356. throw new Predis_ClientException("This pipeline is already opened");
  357. }
  358. $this->_running = $bool;
  359. }
  360. public function execute($block = null) {
  361. if ($block && !is_callable($block)) {
  362. throw new RuntimeException('Argument passed must be a callable object');
  363. }
  364. $this->setRunning(true);
  365. $pipelineBlockException = null;
  366. try {
  367. if ($block !== null) {
  368. $block($this);
  369. }
  370. $this->flushPipeline();
  371. }
  372. catch (Exception $exception) {
  373. $pipelineBlockException = $exception;
  374. }
  375. $this->setRunning(false);
  376. if ($pipelineBlockException !== null) {
  377. throw $pipelineBlockException;
  378. }
  379. return $this->_returnValues;
  380. }
  381. }
  382. class Predis_MultiExecBlock {
  383. private $_redisClient, $_commands, $_initialized;
  384. public function __construct(Predis_Client $redisClient) {
  385. $this->_initialized = false;
  386. $this->_redisClient = $redisClient;
  387. $this->_commands = array();
  388. }
  389. private function initialize() {
  390. if ($this->_initialized === false) {
  391. $this->_redisClient->multi();
  392. $this->_initialized = true;
  393. }
  394. }
  395. public function __call($method, $arguments) {
  396. $this->initialize();
  397. $command = $this->_redisClient->createCommand($method, $arguments);
  398. $response = $this->_redisClient->executeCommand($command);
  399. if (isset($response->queued)) {
  400. $this->_commands[] = $command;
  401. return $response;
  402. }
  403. else {
  404. throw new Predis_ClientException('The server did not respond with a QUEUED status reply');
  405. }
  406. }
  407. public function execute($block = null) {
  408. if ($block && !is_callable($block)) {
  409. throw new RuntimeException('Argument passed must be a callable object');
  410. }
  411. $blockException = null;
  412. $returnValues = array();
  413. try {
  414. if ($block !== null) {
  415. $block($this);
  416. }
  417. $execReply = $this->_redisClient->exec();
  418. $commands = &$this->_commands;
  419. $sizeofReplies = count($execReply);
  420. if ($sizeofReplies !== count($commands)) {
  421. // TODO: think of a better exception message
  422. throw new Predis_ClientException("Out-of-sync");
  423. }
  424. for ($i = 0; $i < $sizeofReplies; $i++) {
  425. $returnValues[] = $commands[$i]->parseResponse($execReply[$i]);
  426. unset($commands[$i]);
  427. }
  428. }
  429. catch (Exception $exception) {
  430. $blockException = $exception;
  431. }
  432. if ($blockException !== null) {
  433. throw $blockException;
  434. }
  435. return $returnValues;
  436. }
  437. }
  438. /* ------------------------------------------------------------------------- */
  439. class Predis_ConnectionParameters {
  440. const DEFAULT_HOST = '127.0.0.1';
  441. const DEFAULT_PORT = 6379;
  442. private $_parameters;
  443. public function __construct($parameters) {
  444. $parameters = $parameters !== null ? $parameters : array();
  445. $this->_parameters = is_array($parameters)
  446. ? self::filterConnectionParams($parameters)
  447. : self::parseURI($parameters);
  448. }
  449. private static function parseURI($uri) {
  450. $parsed = @parse_url($uri);
  451. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  452. throw new Predis_ClientException("Invalid URI: $uri");
  453. }
  454. if (array_key_exists('query', $parsed)) {
  455. $details = array();
  456. foreach (explode('&', $parsed['query']) as $kv) {
  457. list($k, $v) = explode('=', $kv);
  458. switch ($k) {
  459. case 'database':
  460. $details['database'] = $v;
  461. break;
  462. case 'password':
  463. $details['password'] = $v;
  464. break;
  465. case 'connection_timeout':
  466. $details['connection_timeout'] = $v;
  467. break;
  468. case 'read_write_timeout':
  469. $details['read_write_timeout'] = $v;
  470. break;
  471. }
  472. }
  473. $parsed = array_merge($parsed, $details);
  474. }
  475. return self::filterConnectionParams($parsed);
  476. }
  477. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  478. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  479. }
  480. private static function filterConnectionParams($parameters) {
  481. return array(
  482. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  483. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  484. 'database' => self::getParamOrDefault($parameters, 'database'),
  485. 'password' => self::getParamOrDefault($parameters, 'password'),
  486. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout'),
  487. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  488. );
  489. }
  490. public function __get($parameter) {
  491. return $this->_parameters[$parameter];
  492. }
  493. public function __isset($parameter) {
  494. return isset($this->_parameters[$parameter]);
  495. }
  496. }
  497. interface Predis_IConnection {
  498. public function connect();
  499. public function disconnect();
  500. public function isConnected();
  501. public function writeCommand(Predis_Command $command);
  502. public function readResponse(Predis_Command $command);
  503. }
  504. class Predis_Connection implements Predis_IConnection {
  505. const CONNECTION_TIMEOUT = 2;
  506. private $_params, $_socket, $_initCmds;
  507. public function __construct(Predis_ConnectionParameters $parameters) {
  508. $this->_params = $parameters;
  509. $this->_initCmds = array();
  510. }
  511. public function __destruct() {
  512. $this->disconnect();
  513. }
  514. public function isConnected() {
  515. return is_resource($this->_socket);
  516. }
  517. public function connect() {
  518. if ($this->isConnected()) {
  519. throw new Predis_ClientException('Connection already estabilished');
  520. }
  521. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  522. $connectionTimeout = isset($this->_params->connection_timeout)
  523. ? $this->_params->connection_timeout
  524. : self::CONNECTION_TIMEOUT;
  525. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $connectionTimeout);
  526. if (!$this->_socket) {
  527. throw new Predis_ClientException(trim($errstr), $errno);
  528. }
  529. if (isset($this->_params->read_write_timeout)) {
  530. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  531. }
  532. if (count($this->_initCmds) > 0){
  533. $this->sendInitializationCommands();
  534. }
  535. }
  536. public function disconnect() {
  537. if ($this->isConnected()) {
  538. fclose($this->_socket);
  539. }
  540. }
  541. public function pushInitCommand(Predis_Command $command){
  542. $this->_initCmds[] = $command;
  543. }
  544. private function sendInitializationCommands() {
  545. foreach ($this->_initCmds as $command) {
  546. $this->writeCommand($command);
  547. }
  548. foreach ($this->_initCmds as $command) {
  549. $this->readResponse($command);
  550. }
  551. }
  552. public function writeCommand(Predis_Command $command) {
  553. $written = fwrite($this->getSocket(), $command->invoke());
  554. if ($written === false){
  555. throw new Predis_ClientException(sprintf(
  556. 'An error has occurred while writing command %s on the network stream'),
  557. $command->getCommandId()
  558. );
  559. }
  560. }
  561. public function readResponse(Predis_Command $command) {
  562. $response = Predis_Response::read($this->getSocket());
  563. return isset($response->queued) ? $response : $command->parseResponse($response);
  564. }
  565. public function rawCommand($rawCommandData, $closesConnection = false) {
  566. $socket = $this->getSocket();
  567. $written = fwrite($socket, $rawCommandData);
  568. if ($written === false){
  569. throw new Predis_ClientException('An error has occurred while writing a raw command on the network stream');
  570. }
  571. if ($closesConnection) {
  572. return;
  573. }
  574. return Predis_Response::read($socket);
  575. }
  576. public function getSocket() {
  577. if (!$this->isConnected()) {
  578. $this->connect();
  579. }
  580. return $this->_socket;
  581. }
  582. public function __toString() {
  583. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  584. }
  585. }
  586. class Predis_ConnectionCluster implements Predis_IConnection, IteratorAggregate {
  587. // TODO: find a clean way to handle connection failures of single nodes.
  588. private $_pool, $_ring;
  589. public function __construct() {
  590. $this->_pool = array();
  591. $this->_ring = new Utilities_HashRing();
  592. }
  593. public function __destruct() {
  594. $this->disconnect();
  595. }
  596. public function isConnected() {
  597. foreach ($this->_pool as $connection) {
  598. if ($connection->isConnected()) {
  599. return true;
  600. }
  601. }
  602. return false;
  603. }
  604. public function connect() {
  605. foreach ($this->_pool as $connection) {
  606. $connection->connect();
  607. }
  608. }
  609. public function disconnect() {
  610. foreach ($this->_pool as $connection) {
  611. $connection->disconnect();
  612. }
  613. }
  614. public function add(Predis_Connection $connection) {
  615. $this->_pool[] = $connection;
  616. $this->_ring->add($connection);
  617. }
  618. private function getConnection(Predis_Command $command) {
  619. if ($command->canBeHashed() === false) {
  620. throw new Predis_ClientException(
  621. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  622. );
  623. }
  624. return $this->_ring->get($command->getHash());
  625. }
  626. public function getConnectionById($id = null) {
  627. return $this->_pool[$id === null ? 0 : $id];
  628. }
  629. public function getIterator() {
  630. return new ArrayIterator($this->_pool);
  631. }
  632. public function writeCommand(Predis_Command $command) {
  633. $this->getConnection($command)->writeCommand($command);
  634. }
  635. public function readResponse(Predis_Command $command) {
  636. return $this->getConnection($command)->readResponse($command);
  637. }
  638. }
  639. /* ------------------------------------------------------------------------- */
  640. abstract class Predis_RedisServerProfile {
  641. private static $_serverProfiles;
  642. private $_registeredCommands;
  643. public function __construct() {
  644. $this->_registeredCommands = $this->getSupportedCommands();
  645. }
  646. public abstract function getVersion();
  647. protected abstract function getSupportedCommands();
  648. public static function getDefault() {
  649. return self::get('default');
  650. }
  651. private static function predisServerProfiles() {
  652. return array(
  653. '1.0' => 'Predis_RedisServer_v1_0',
  654. '1.2' => 'Predis_RedisServer_v1_2',
  655. 'default' => 'Predis_RedisServer_v1_2',
  656. 'dev' => 'Predis_RedisServer_vNext',
  657. );
  658. }
  659. public static function get($version) {
  660. if (!isset(self::$_serverProfiles)) {
  661. self::$_serverProfiles = self::predisServerProfiles();
  662. }
  663. if (!isset(self::$_serverProfiles[$version])) {
  664. throw new Predis_ClientException("Unknown server profile: $version");
  665. }
  666. $profile = self::$_serverProfiles[$version];
  667. return new $profile();
  668. }
  669. public function compareWith($version, $operator = null) {
  670. // one could expect that PHP's version_compare would behave
  671. // the same way if invoked with 2 arguments or 3 arguments
  672. // with the third being NULL, but it is not like that.
  673. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  674. // we might need to revise the behavior of this method.
  675. return ($operator === null
  676. ? version_compare($this, $version)
  677. : version_compare($this, $version, $operator)
  678. );
  679. }
  680. public function supportsCommand($command) {
  681. return isset($this->_registeredCommands[$command]);
  682. }
  683. public function createCommand($method, $arguments = array()) {
  684. if (!isset($this->_registeredCommands[$method])) {
  685. throw new Predis_ClientException("'$method' is not a registered Redis command");
  686. }
  687. $commandClass = $this->_registeredCommands[$method];
  688. $command = new $commandClass();
  689. $command->setArgumentsArray($arguments);
  690. return $command;
  691. }
  692. public function registerCommands(Array $commands) {
  693. foreach ($commands as $command => $aliases) {
  694. $this->registerCommand($command, $aliases);
  695. }
  696. }
  697. public function registerCommand($command, $aliases) {
  698. $commandReflection = new ReflectionClass($command);
  699. if (!$commandReflection->isSubclassOf('Predis_Command')) {
  700. throw new Predis_ClientException("Cannot register '$command' as it is not a valid Redis command");
  701. }
  702. if (is_array($aliases)) {
  703. foreach ($aliases as $alias) {
  704. $this->_registeredCommands[$alias] = $command;
  705. }
  706. }
  707. else {
  708. $this->_registeredCommands[$aliases] = $command;
  709. }
  710. }
  711. public function __toString() {
  712. return $this->getVersion();
  713. }
  714. }
  715. class Predis_RedisServer_v1_0 extends Predis_RedisServerProfile {
  716. public function getVersion() { return '1.0'; }
  717. public function getSupportedCommands() {
  718. return array(
  719. /* miscellaneous commands */
  720. 'ping' => 'Predis_Commands_Ping',
  721. 'echo' => 'Predis_Commands_DoEcho',
  722. 'auth' => 'Predis_Commands_Auth',
  723. /* connection handling */
  724. 'quit' => 'Predis_Commands_Quit',
  725. /* commands operating on string values */
  726. 'set' => 'Predis_Commands_Set',
  727. 'setnx' => 'Predis_Commands_SetPreserve',
  728. 'setPreserve' => 'Predis_Commands_SetPreserve',
  729. 'get' => 'Predis_Commands_Get',
  730. 'mget' => 'Predis_Commands_GetMultiple',
  731. 'getMultiple' => 'Predis_Commands_GetMultiple',
  732. 'getset' => 'Predis_Commands_GetSet',
  733. 'getSet' => 'Predis_Commands_GetSet',
  734. 'incr' => 'Predis_Commands_Increment',
  735. 'increment' => 'Predis_Commands_Increment',
  736. 'incrby' => 'Predis_Commands_IncrementBy',
  737. 'incrementBy' => 'Predis_Commands_IncrementBy',
  738. 'decr' => 'Predis_Commands_Decrement',
  739. 'decrement' => 'Predis_Commands_Decrement',
  740. 'decrby' => 'Predis_Commands_DecrementBy',
  741. 'decrementBy' => 'Predis_Commands_DecrementBy',
  742. 'exists' => 'Predis_Commands_Exists',
  743. 'del' => 'Predis_Commands_Delete',
  744. 'delete' => 'Predis_Commands_Delete',
  745. 'type' => 'Predis_Commands_Type',
  746. /* commands operating on the key space */
  747. 'keys' => 'Predis_Commands_Keys',
  748. 'randomkey' => 'Predis_Commands_RandomKey',
  749. 'randomKey' => 'Predis_Commands_RandomKey',
  750. 'rename' => 'Predis_Commands_Rename',
  751. 'renamenx' => 'Predis_Commands_RenamePreserve',
  752. 'renamePreserve' => 'Predis_Commands_RenamePreserve',
  753. 'expire' => 'Predis_Commands_Expire',
  754. 'expireat' => 'Predis_Commands_ExpireAt',
  755. 'expireAt' => 'Predis_Commands_ExpireAt',
  756. 'dbsize' => 'Predis_Commands_DatabaseSize',
  757. 'databaseSize' => 'Predis_Commands_DatabaseSize',
  758. 'ttl' => 'Predis_Commands_TimeToLive',
  759. 'timeToLive' => 'Predis_Commands_TimeToLive',
  760. /* commands operating on lists */
  761. 'rpush' => 'Predis_Commands_ListPushTail',
  762. 'pushTail' => 'Predis_Commands_ListPushTail',
  763. 'lpush' => 'Predis_Commands_ListPushHead',
  764. 'pushHead' => 'Predis_Commands_ListPushHead',
  765. 'llen' => 'Predis_Commands_ListLength',
  766. 'listLength' => 'Predis_Commands_ListLength',
  767. 'lrange' => 'Predis_Commands_ListRange',
  768. 'listRange' => 'Predis_Commands_ListRange',
  769. 'ltrim' => 'Predis_Commands_ListTrim',
  770. 'listTrim' => 'Predis_Commands_ListTrim',
  771. 'lindex' => 'Predis_Commands_ListIndex',
  772. 'listIndex' => 'Predis_Commands_ListIndex',
  773. 'lset' => 'Predis_Commands_ListSet',
  774. 'listSet' => 'Predis_Commands_ListSet',
  775. 'lrem' => 'Predis_Commands_ListRemove',
  776. 'listRemove' => 'Predis_Commands_ListRemove',
  777. 'lpop' => 'Predis_Commands_ListPopFirst',
  778. 'popFirst' => 'Predis_Commands_ListPopFirst',
  779. 'rpop' => 'Predis_Commands_ListPopLast',
  780. 'popLast' => 'Predis_Commands_ListPopLast',
  781. /* commands operating on sets */
  782. 'sadd' => 'Predis_Commands_SetAdd',
  783. 'setAdd' => 'Predis_Commands_SetAdd',
  784. 'srem' => 'Predis_Commands_SetRemove',
  785. 'setRemove' => 'Predis_Commands_SetRemove',
  786. 'spop' => 'Predis_Commands_SetPop',
  787. 'setPop' => 'Predis_Commands_SetPop',
  788. 'smove' => 'Predis_Commands_SetMove',
  789. 'setMove' => 'Predis_Commands_SetMove',
  790. 'scard' => 'Predis_Commands_SetCardinality',
  791. 'setCardinality' => 'Predis_Commands_SetCardinality',
  792. 'sismember' => 'Predis_Commands_SetIsMember',
  793. 'setIsMember' => 'Predis_Commands_SetIsMember',
  794. 'sinter' => 'Predis_Commands_SetIntersection',
  795. 'setIntersection' => 'Predis_Commands_SetIntersection',
  796. 'sinterstore' => 'Predis_Commands_SetIntersectionStore',
  797. 'setIntersectionStore' => 'Predis_Commands_SetIntersectionStore',
  798. 'sunion' => 'Predis_Commands_SetUnion',
  799. 'setUnion' => 'Predis_Commands_SetUnion',
  800. 'sunionstore' => 'Predis_Commands_SetUnionStore',
  801. 'setUnionStore' => 'Predis_Commands_SetUnionStore',
  802. 'sdiff' => 'Predis_Commands_SetDifference',
  803. 'setDifference' => 'Predis_Commands_SetDifference',
  804. 'sdiffstore' => 'Predis_Commands_SetDifferenceStore',
  805. 'setDifferenceStore' => 'Predis_Commands_SetDifferenceStore',
  806. 'smembers' => 'Predis_Commands_SetMembers',
  807. 'setMembers' => 'Predis_Commands_SetMembers',
  808. 'srandmember' => 'Predis_Commands_SetRandomMember',
  809. 'setRandomMember' => 'Predis_Commands_SetRandomMember',
  810. /* multiple databases handling commands */
  811. 'select' => 'Predis_Commands_SelectDatabase',
  812. 'selectDatabase' => 'Predis_Commands_SelectDatabase',
  813. 'move' => 'Predis_Commands_MoveKey',
  814. 'moveKey' => 'Predis_Commands_MoveKey',
  815. 'flushdb' => 'Predis_Commands_FlushDatabase',
  816. 'flushDatabase' => 'Predis_Commands_FlushDatabase',
  817. 'flushall' => 'Predis_Commands_FlushAll',
  818. 'flushDatabases' => 'Predis_Commands_FlushAll',
  819. /* sorting */
  820. 'sort' => 'Predis_Commands_Sort',
  821. /* remote server control commands */
  822. 'info' => 'Predis_Commands_Info',
  823. 'slaveof' => 'Predis_Commands_SlaveOf',
  824. 'slaveOf' => 'Predis_Commands_SlaveOf',
  825. /* persistence control commands */
  826. 'save' => 'Predis_Commands_Save',
  827. 'bgsave' => 'Predis_Commands_BackgroundSave',
  828. 'backgroundSave' => 'Predis_Commands_BackgroundSave',
  829. 'lastsave' => 'Predis_Commands_LastSave',
  830. 'lastSave' => 'Predis_Commands_LastSave',
  831. 'shutdown' => 'Predis_Commands_Shutdown',
  832. );
  833. }
  834. }
  835. class Predis_RedisServer_v1_2 extends Predis_RedisServer_v1_0 {
  836. public function getVersion() { return '1.2'; }
  837. public function getSupportedCommands() {
  838. return array_merge(parent::getSupportedCommands(), array(
  839. /* commands operating on string values */
  840. 'mset' => 'Predis_Commands_SetMultiple',
  841. 'setMultiple' => 'Predis_Commands_SetMultiple',
  842. 'msetnx' => 'Predis_Commands_SetMultiplePreserve',
  843. 'setMultiplePreserve' => 'Predis_Commands_SetMultiplePreserve',
  844. /* commands operating on lists */
  845. 'rpoplpush' => 'Predis_Commands_ListPushTailPopFirst',
  846. 'listPopLastPushHead' => 'Predis_Commands_ListPopLastPushHead',
  847. /* commands operating on sorted sets */
  848. 'zadd' => 'Predis_Commands_ZSetAdd',
  849. 'zsetAdd' => 'Predis_Commands_ZSetAdd',
  850. 'zincrby' => 'Predis_Commands_ZSetIncrementBy',
  851. 'zsetIncrementBy' => 'Predis_Commands_ZSetIncrementBy',
  852. 'zrem' => 'Predis_Commands_ZSetRemove',
  853. 'zsetRemove' => 'Predis_Commands_ZSetRemove',
  854. 'zrange' => 'Predis_Commands_ZSetRange',
  855. 'zsetRange' => 'Predis_Commands_ZSetRange',
  856. 'zrevrange' => 'Predis_Commands_ZSetReverseRange',
  857. 'zsetReverseRange' => 'Predis_Commands_ZSetReverseRange',
  858. 'zrangebyscore' => 'Predis_Commands_ZSetRangeByScore',
  859. 'zsetRangeByScore' => 'Predis_Commands_ZSetRangeByScore',
  860. 'zcard' => 'Predis_Commands_ZSetCardinality',
  861. 'zsetCardinality' => 'Predis_Commands_ZSetCardinality',
  862. 'zscore' => 'Predis_Commands_ZSetScore',
  863. 'zsetScore' => 'Predis_Commands_ZSetScore',
  864. 'zremrangebyscore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  865. 'zsetRemoveRangeByScore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  866. /* persistence control commands */
  867. 'bgrewriteaof' => 'Predis_Commands_BackgroundRewriteAppendOnlyFile',
  868. 'backgroundRewriteAppendOnlyFile' => 'Predis_Commands_BackgroundRewriteAppendOnlyFile',
  869. ));
  870. }
  871. }
  872. class Predis_RedisServer_vNext extends Predis_RedisServer_v1_2 {
  873. public function getVersion() { return '1.3'; }
  874. public function getSupportedCommands() {
  875. return array_merge(parent::getSupportedCommands(), array(
  876. /* miscellaneous commands */
  877. 'multi' => 'Predis_Commands_Multi',
  878. 'exec' => 'Predis_Commands_Exec',
  879. /* commands operating on lists */
  880. 'blpop' => 'Predis_Commands_ListPopFirstBlocking',
  881. 'popFirstBlocking' => 'Predis_Commands_ListPopFirstBlocking',
  882. 'brpop' => 'Predis_Commands_ListPopLastBlocking',
  883. 'popLastBlocking' => 'Predis_Commands_ListPopLastBlocking',
  884. ));
  885. }
  886. }
  887. /* ------------------------------------------------------------------------- */
  888. class Utilities_HashRing {
  889. const DEFAULT_REPLICAS = 128;
  890. private $_ring, $_ringKeys, $_replicas;
  891. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  892. $this->_replicas = $replicas;
  893. $this->_ring = array();
  894. $this->_ringKeys = array();
  895. }
  896. public function add($node) {
  897. $nodeHash = (string) $node;
  898. $replicas = $this->_replicas;
  899. for ($i = 0; $i < $replicas; $i++) {
  900. $key = crc32($nodeHash . ':' . $i);
  901. $this->_ring[$key] = $node;
  902. }
  903. ksort($this->_ring, SORT_NUMERIC);
  904. $this->_ringKeys = array_keys($this->_ring);
  905. }
  906. public function remove($node) {
  907. $nodeHash = (string) $node;
  908. $replicas = $this->_replicas;
  909. for ($i = 0; $i < $replicas; $i++) {
  910. $key = crc32($nodeHash . ':' . $i);
  911. unset($this->_ring[$key]);
  912. $newRing = array();
  913. foreach ($this->_ringKeys as $rk) {
  914. if ($rk !== $key) {
  915. $newRing[] = $rk;
  916. }
  917. }
  918. $this->_ringKeys = $newRing;
  919. }
  920. }
  921. public function get($key) {
  922. return $this->_ring[$this->getNodeKey($key)];
  923. }
  924. private function getNodeKey($key) {
  925. $ringKeys = $this->_ringKeys;
  926. $upper = count($ringKeys) - 1;
  927. $lower = 0;
  928. $index = 0;
  929. while ($lower <= $upper) {
  930. $index = ($lower + $upper) / 2;
  931. $item = $ringKeys[$index];
  932. if ($item > $key) {
  933. $upper = $index - 1;
  934. }
  935. else if ($item < $key) {
  936. $lower = $index + 1;
  937. }
  938. else {
  939. return $index;
  940. }
  941. }
  942. return $ringKeys[$upper];
  943. }
  944. }
  945. /* ------------------------------------------------------------------------- */
  946. /* miscellaneous commands */
  947. class Predis_Commands_Ping extends Predis_InlineCommand {
  948. public function canBeHashed() { return false; }
  949. public function getCommandId() { return 'PING'; }
  950. public function parseResponse($data) {
  951. return $data === 'PONG' ? true : false;
  952. }
  953. }
  954. class Predis_Commands_DoEcho extends Predis_BulkCommand {
  955. public function canBeHashed() { return false; }
  956. public function getCommandId() { return 'ECHO'; }
  957. }
  958. class Predis_Commands_Auth extends Predis_InlineCommand {
  959. public function canBeHashed() { return false; }
  960. public function getCommandId() { return 'AUTH'; }
  961. }
  962. /* connection handling */
  963. class Predis_Commands_Quit extends Predis_InlineCommand {
  964. public function canBeHashed() { return false; }
  965. public function getCommandId() { return 'QUIT'; }
  966. public function closesConnection() { return true; }
  967. }
  968. /* commands operating on string values */
  969. class Predis_Commands_Set extends Predis_BulkCommand {
  970. public function getCommandId() { return 'SET'; }
  971. }
  972. class Predis_Commands_SetPreserve extends Predis_BulkCommand {
  973. public function getCommandId() { return 'SETNX'; }
  974. public function parseResponse($data) { return (bool) $data; }
  975. }
  976. class Predis_Commands_SetMultiple extends Predis_MultiBulkCommand {
  977. public function canBeHashed() { return false; }
  978. public function getCommandId() { return 'MSET'; }
  979. }
  980. class Predis_Commands_SetMultiplePreserve extends Predis_MultiBulkCommand {
  981. public function canBeHashed() { return false; }
  982. public function getCommandId() { return 'MSETNX'; }
  983. public function parseResponse($data) { return (bool) $data; }
  984. }
  985. class Predis_Commands_Get extends Predis_InlineCommand {
  986. public function getCommandId() { return 'GET'; }
  987. }
  988. class Predis_Commands_GetMultiple extends Predis_InlineCommand {
  989. public function canBeHashed() { return false; }
  990. public function getCommandId() { return 'MGET'; }
  991. }
  992. class Predis_Commands_GetSet extends Predis_BulkCommand {
  993. public function getCommandId() { return 'GETSET'; }
  994. }
  995. class Predis_Commands_Increment extends Predis_InlineCommand {
  996. public function getCommandId() { return 'INCR'; }
  997. }
  998. class Predis_Commands_IncrementBy extends Predis_InlineCommand {
  999. public function getCommandId() { return 'INCRBY'; }
  1000. }
  1001. class Predis_Commands_Decrement extends Predis_InlineCommand {
  1002. public function getCommandId() { return 'DECR'; }
  1003. }
  1004. class Predis_Commands_DecrementBy extends Predis_InlineCommand {
  1005. public function getCommandId() { return 'DECRBY'; }
  1006. }
  1007. class Predis_Commands_Exists extends Predis_InlineCommand {
  1008. public function getCommandId() { return 'EXISTS'; }
  1009. public function parseResponse($data) { return (bool) $data; }
  1010. }
  1011. class Predis_Commands_Delete extends Predis_InlineCommand {
  1012. public function getCommandId() { return 'DEL'; }
  1013. public function parseResponse($data) { return (bool) $data; }
  1014. }
  1015. class Predis_Commands_Type extends Predis_InlineCommand {
  1016. public function getCommandId() { return 'TYPE'; }
  1017. }
  1018. /* commands operating on the key space */
  1019. class Predis_Commands_Keys extends Predis_InlineCommand {
  1020. public function canBeHashed() { return false; }
  1021. public function getCommandId() { return 'KEYS'; }
  1022. public function parseResponse($data) {
  1023. // TODO: is this behaviour correct?
  1024. return strlen($data) > 0 ? explode(' ', $data) : array();
  1025. }
  1026. }
  1027. class Predis_Commands_RandomKey extends Predis_InlineCommand {
  1028. public function canBeHashed() { return false; }
  1029. public function getCommandId() { return 'RANDOMKEY'; }
  1030. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1031. }
  1032. class Predis_Commands_Rename extends Predis_InlineCommand {
  1033. public function canBeHashed() { return false; }
  1034. public function getCommandId() { return 'RENAME'; }
  1035. }
  1036. class Predis_Commands_RenamePreserve extends Predis_InlineCommand {
  1037. public function canBeHashed() { return false; }
  1038. public function getCommandId() { return 'RENAMENX'; }
  1039. public function parseResponse($data) { return (bool) $data; }
  1040. }
  1041. class Predis_Commands_Expire extends Predis_InlineCommand {
  1042. public function getCommandId() { return 'EXPIRE'; }
  1043. public function parseResponse($data) { return (bool) $data; }
  1044. }
  1045. class Predis_Commands_ExpireAt extends Predis_InlineCommand {
  1046. public function getCommandId() { return 'EXPIREAT'; }
  1047. public function parseResponse($data) { return (bool) $data; }
  1048. }
  1049. class Predis_Commands_DatabaseSize extends Predis_InlineCommand {
  1050. public function canBeHashed() { return false; }
  1051. public function getCommandId() { return 'DBSIZE'; }
  1052. }
  1053. class Predis_Commands_TimeToLive extends Predis_InlineCommand {
  1054. public function getCommandId() { return 'TTL'; }
  1055. }
  1056. /* commands operating on lists */
  1057. class Predis_Commands_ListPushTail extends Predis_BulkCommand {
  1058. public function getCommandId() { return 'RPUSH'; }
  1059. }
  1060. class Predis_Commands_ListPushHead extends Predis_BulkCommand {
  1061. public function getCommandId() { return 'LPUSH'; }
  1062. }
  1063. class Predis_Commands_ListLength extends Predis_InlineCommand {
  1064. public function getCommandId() { return 'LLEN'; }
  1065. }
  1066. class Predis_Commands_ListRange extends Predis_InlineCommand {
  1067. public function getCommandId() { return 'LRANGE'; }
  1068. }
  1069. class Predis_Commands_ListTrim extends Predis_InlineCommand {
  1070. public function getCommandId() { return 'LTRIM'; }
  1071. }
  1072. class Predis_Commands_ListIndex extends Predis_InlineCommand {
  1073. public function getCommandId() { return 'LINDEX'; }
  1074. }
  1075. class Predis_Commands_ListSet extends Predis_BulkCommand {
  1076. public function getCommandId() { return 'LSET'; }
  1077. }
  1078. class Predis_Commands_ListRemove extends Predis_BulkCommand {
  1079. public function getCommandId() { return 'LREM'; }
  1080. }
  1081. class Predis_Commands_ListPopLastPushHead extends Predis_InlineCommand {
  1082. public function getCommandId() { return 'RPOPLPUSH'; }
  1083. }
  1084. class Predis_Commands_ListPopLastPushHeadBulk extends Predis_BulkCommand {
  1085. public function getCommandId() { return 'RPOPLPUSH'; }
  1086. }
  1087. class Predis_Commands_ListPopFirst extends Predis_InlineCommand {
  1088. public function getCommandId() { return 'LPOP'; }
  1089. }
  1090. class Predis_Commands_ListPopLast extends Predis_InlineCommand {
  1091. public function getCommandId() { return 'RPOP'; }
  1092. }
  1093. class Predis_Commands_ListPopFirstBlocking extends Predis_InlineCommand {
  1094. public function getCommandId() { return 'BLPOP'; }
  1095. }
  1096. class Predis_Commands_ListPopLastBlocking extends Predis_InlineCommand {
  1097. public function getCommandId() { return 'BRPOP'; }
  1098. }
  1099. /* commands operating on sets */
  1100. class Predis_Commands_SetAdd extends Predis_BulkCommand {
  1101. public function getCommandId() { return 'SADD'; }
  1102. public function parseResponse($data) { return (bool) $data; }
  1103. }
  1104. class Predis_Commands_SetRemove extends Predis_BulkCommand {
  1105. public function getCommandId() { return 'SREM'; }
  1106. public function parseResponse($data) { return (bool) $data; }
  1107. }
  1108. class Predis_Commands_SetPop extends Predis_InlineCommand {
  1109. public function getCommandId() { return 'SPOP'; }
  1110. }
  1111. class Predis_Commands_SetMove extends Predis_BulkCommand {
  1112. public function canBeHashed() { return false; }
  1113. public function getCommandId() { return 'SMOVE'; }
  1114. public function parseResponse($data) { return (bool) $data; }
  1115. }
  1116. class Predis_Commands_SetCardinality extends Predis_InlineCommand {
  1117. public function getCommandId() { return 'SCARD'; }
  1118. }
  1119. class Predis_Commands_SetIsMember extends Predis_BulkCommand {
  1120. public function getCommandId() { return 'SISMEMBER'; }
  1121. public function parseResponse($data) { return (bool) $data; }
  1122. }
  1123. class Predis_Commands_SetIntersection extends Predis_InlineCommand {
  1124. public function getCommandId() { return 'SINTER'; }
  1125. }
  1126. class Predis_Commands_SetIntersectionStore extends Predis_InlineCommand {
  1127. public function getCommandId() { return 'SINTERSTORE'; }
  1128. }
  1129. class Predis_Commands_SetUnion extends Predis_InlineCommand {
  1130. public function getCommandId() { return 'SUNION'; }
  1131. }
  1132. class Predis_Commands_SetUnionStore extends Predis_InlineCommand {
  1133. public function getCommandId() { return 'SUNIONSTORE'; }
  1134. }
  1135. class Predis_Commands_SetDifference extends Predis_InlineCommand {
  1136. public function getCommandId() { return 'SDIFF'; }
  1137. }
  1138. class Predis_Commands_SetDifferenceStore extends Predis_InlineCommand {
  1139. public function getCommandId() { return 'SDIFFSTORE'; }
  1140. }
  1141. class Predis_Commands_SetMembers extends Predis_InlineCommand {
  1142. public function getCommandId() { return 'SMEMBERS'; }
  1143. }
  1144. class Predis_Commands_SetRandomMember extends Predis_InlineCommand {
  1145. public function getCommandId() { return 'SRANDMEMBER'; }
  1146. }
  1147. /* commands operating on sorted sets */
  1148. class Predis_Commands_ZSetAdd extends Predis_BulkCommand {
  1149. public function getCommandId() { return 'ZADD'; }
  1150. public function parseResponse($data) { return (bool) $data; }
  1151. }
  1152. class Predis_Commands_ZSetIncrementBy extends Predis_BulkCommand {
  1153. public function getCommandId() { return 'ZINCRBY'; }
  1154. }
  1155. class Predis_Commands_ZSetRemove extends Predis_BulkCommand {
  1156. public function getCommandId() { return 'ZREM'; }
  1157. public function parseResponse($data) { return (bool) $data; }
  1158. }
  1159. class Predis_Commands_ZSetRange extends Predis_InlineCommand {
  1160. public function getCommandId() { return 'ZRANGE'; }
  1161. public function parseResponse($data) {
  1162. $arguments = $this->getArguments();
  1163. if (count($arguments) === 4) {
  1164. if (strtolower($arguments[3]) === 'withscores') {
  1165. $result = array();
  1166. for ($i = 0; $i < count($data); $i++) {
  1167. $result[] = array($data[$i], $data[++$i]);
  1168. }
  1169. return $result;
  1170. }
  1171. }
  1172. return $data;
  1173. }
  1174. }
  1175. class Predis_Commands_ZSetReverseRange extends Predis_Commands_ZSetRange {
  1176. public function getCommandId() { return 'ZREVRANGE'; }
  1177. }
  1178. class Predis_Commands_ZSetRangeByScore extends Predis_InlineCommand {
  1179. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1180. }
  1181. class Predis_Commands_ZSetCardinality extends Predis_InlineCommand {
  1182. public function getCommandId() { return 'ZCARD'; }
  1183. }
  1184. class Predis_Commands_ZSetScore extends Predis_BulkCommand {
  1185. public function getCommandId() { return 'ZSCORE'; }
  1186. }
  1187. class Predis_Commands_ZSetRemoveRangeByScore extends Predis_InlineCommand {
  1188. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1189. }
  1190. /* multiple databases handling commands */
  1191. class Predis_Commands_SelectDatabase extends Predis_InlineCommand {
  1192. public function canBeHashed() { return false; }
  1193. public function getCommandId() { return 'SELECT'; }
  1194. }
  1195. class Predis_Commands_MoveKey extends Predis_InlineCommand {
  1196. public function canBeHashed() { return false; }
  1197. public function getCommandId() { return 'MOVE'; }
  1198. public function parseResponse($data) { return (bool) $data; }
  1199. }
  1200. class Predis_Commands_FlushDatabase extends Predis_InlineCommand {
  1201. public function canBeHashed() { return false; }
  1202. public function getCommandId() { return 'FLUSHDB'; }
  1203. }
  1204. class Predis_Commands_FlushAll extends Predis_InlineCommand {
  1205. public function canBeHashed() { return false; }
  1206. public function getCommandId() { return 'FLUSHALL'; }
  1207. }
  1208. /* sorting */
  1209. class Predis_Commands_Sort extends Predis_InlineCommand {
  1210. public function getCommandId() { return 'SORT'; }
  1211. public function filterArguments(Array $arguments) {
  1212. if (count($arguments) === 1) {
  1213. return $arguments;
  1214. }
  1215. // TODO: add more parameters checks
  1216. $query = array($arguments[0]);
  1217. $sortParams = $arguments[1];
  1218. if (isset($sortParams['by'])) {
  1219. $query[] = 'BY ' . $sortParams['by'];
  1220. }
  1221. if (isset($sortParams['get'])) {
  1222. $query[] = 'GET ' . $sortParams['get'];
  1223. }
  1224. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1225. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1226. }
  1227. if (isset($sortParams['sort'])) {
  1228. $query[] = strtoupper($sortParams['sort']);
  1229. }
  1230. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1231. $query[] = 'ALPHA';
  1232. }
  1233. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1234. $query[] = 'STORE ' . $sortParams['store'];
  1235. }
  1236. return $query;
  1237. }
  1238. }
  1239. /* persistence control commands */
  1240. class Predis_Commands_Save extends Predis_InlineCommand {
  1241. public function canBeHashed() { return false; }
  1242. public function getCommandId() { return 'SAVE'; }
  1243. }
  1244. class Predis_Commands_BackgroundSave extends Predis_InlineCommand {
  1245. public function canBeHashed() { return false; }
  1246. public function getCommandId() { return 'BGSAVE'; }
  1247. public function parseResponse($data) {
  1248. if ($data == 'Background saving started') {
  1249. return true;
  1250. }
  1251. return $data;
  1252. }
  1253. }
  1254. class Predis_Commands_BackgroundRewriteAppendOnlyFile extends Predis_InlineCommand {
  1255. public function canBeHashed() { return false; }
  1256. public function getCommandId() { return 'BGREWRITEAOF'; }
  1257. public function parseResponse($data) {
  1258. return $data == 'Background append only file rewriting started';
  1259. }
  1260. }
  1261. class Predis_Commands_LastSave extends Predis_InlineCommand {
  1262. public function canBeHashed() { return false; }
  1263. public function getCommandId() { return 'LASTSAVE'; }
  1264. }
  1265. class Predis_Commands_Shutdown extends Predis_InlineCommand {
  1266. public function canBeHashed() { return false; }
  1267. public function getCommandId() { return 'SHUTDOWN'; }
  1268. public function closesConnection() { return true; }
  1269. }
  1270. /* remote server control commands */
  1271. class Predis_Commands_Info extends Predis_InlineCommand {
  1272. public function canBeHashed() { return false; }
  1273. public function getCommandId() { return 'INFO'; }
  1274. public function parseResponse($data) {
  1275. $info = array();
  1276. $infoLines = explode("\r\n", $data, -1);
  1277. foreach ($infoLines as $row) {
  1278. list($k, $v) = explode(':', $row);
  1279. if (!preg_match('/^db\d+$/', $k)) {
  1280. $info[$k] = $v;
  1281. }
  1282. else {
  1283. $db = array();
  1284. foreach (explode(',', $v) as $dbvar) {
  1285. list($dbvk, $dbvv) = explode('=', $dbvar);
  1286. $db[trim($dbvk)] = $dbvv;
  1287. }
  1288. $info[$k] = $db;
  1289. }
  1290. }
  1291. return $info;
  1292. }
  1293. }
  1294. class Predis_Commands_SlaveOf extends Predis_InlineCommand {
  1295. public function canBeHashed() { return false; }
  1296. public function getCommandId() { return 'SLAVEOF'; }
  1297. public function filterArguments(Array $arguments) {
  1298. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1299. }
  1300. }
  1301. class Predis_Commands_Multi extends Predis_InlineCommand {
  1302. public function canBeHashed() { return false; }
  1303. public function getCommandId() { return 'MULTI'; }
  1304. }
  1305. class Predis_Commands_Exec extends Predis_InlineCommand {
  1306. public function canBeHashed() { return false; }
  1307. public function getCommandId() { return 'EXEC'; }
  1308. }
  1309. ?>