Predis.php 54 KB

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