Predis.php 54 KB

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