Predis.php 49 KB

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