Predis.php 47 KB

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