Predis.php 48 KB

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