Predis.php 53 KB

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