Predis.php 47 KB

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