Predis.php 56 KB

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