Predis.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  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. public function __isset($parameter) {
  418. return isset($this->_parameters[$parameter]);
  419. }
  420. }
  421. interface IConnection {
  422. public function connect();
  423. public function disconnect();
  424. public function isConnected();
  425. public function writeCommand(Command $command);
  426. public function readResponse(Command $command);
  427. }
  428. class Connection implements IConnection {
  429. const CONNECTION_TIMEOUT = 2;
  430. private $_params, $_socket, $_initCmds;
  431. public function __construct(ConnectionParameters $parameters) {
  432. $this->_params = $parameters;
  433. $this->_initCmds = array();
  434. }
  435. public function __destruct() {
  436. $this->disconnect();
  437. }
  438. public function isConnected() {
  439. return is_resource($this->_socket);
  440. }
  441. public function connect() {
  442. if ($this->isConnected()) {
  443. throw new ClientException('Connection already estabilished');
  444. }
  445. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  446. $connectionTimeout = $this->_params->connection_timeout ?: self::CONNECTION_TIMEOUT;
  447. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $connectionTimeout);
  448. if (!$this->_socket) {
  449. throw new ClientException(trim($errstr), $errno);
  450. }
  451. if (isset($this->_params->read_write_timeout)) {
  452. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  453. }
  454. if (count($this->_initCmds) > 0){
  455. $this->sendInitializationCommands();
  456. }
  457. }
  458. public function disconnect() {
  459. if ($this->isConnected()) {
  460. fclose($this->_socket);
  461. }
  462. }
  463. public function pushInitCommand(Command $command){
  464. $this->_initCmds[] = $command;
  465. }
  466. private function sendInitializationCommands() {
  467. foreach ($this->_initCmds as $command) {
  468. $this->writeCommand($command);
  469. }
  470. foreach ($this->_initCmds as $command) {
  471. $this->readResponse($command);
  472. }
  473. }
  474. public function writeCommand(Command $command) {
  475. fwrite($this->getSocket(), $command());
  476. }
  477. public function readResponse(Command $command) {
  478. $socket = $this->getSocket();
  479. $handler = Response::getPrefixHandler(fgetc($socket));
  480. $response = $command->parseResponse($handler($socket));
  481. return $response;
  482. }
  483. public function rawCommand($rawCommandData, $closesConnection = false) {
  484. $socket = $this->getSocket();
  485. fwrite($socket, $rawCommandData);
  486. if ($closesConnection) {
  487. return;
  488. }
  489. $handler = Response::getPrefixHandler(fgetc($socket));
  490. return $handler($socket);
  491. }
  492. public function getSocket() {
  493. if (!$this->isConnected()) {
  494. $this->connect();
  495. }
  496. return $this->_socket;
  497. }
  498. public function __toString() {
  499. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  500. }
  501. }
  502. class ConnectionCluster implements IConnection, \IteratorAggregate {
  503. // TODO: find a clean way to handle connection failures of single nodes.
  504. private $_pool, $_ring;
  505. public function __construct() {
  506. $this->_pool = array();
  507. $this->_ring = new Utilities\HashRing();
  508. }
  509. public function __destruct() {
  510. $this->disconnect();
  511. }
  512. public function isConnected() {
  513. foreach ($this->_pool as $connection) {
  514. if ($connection->isConnected()) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. public function connect() {
  521. foreach ($this->_pool as $connection) {
  522. $connection->connect();
  523. }
  524. }
  525. public function disconnect() {
  526. foreach ($this->_pool as $connection) {
  527. $connection->disconnect();
  528. }
  529. }
  530. public function add(Connection $connection) {
  531. $this->_pool[] = $connection;
  532. $this->_ring->add($connection);
  533. }
  534. private function getConnection(Command $command) {
  535. if ($command->canBeHashed() === false) {
  536. throw new ClientException(
  537. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  538. );
  539. }
  540. return $this->_ring->get($command->getHash());
  541. }
  542. public function getConnectionById($id = null) {
  543. return $this->_pool[$id === null ? 0 : $id];
  544. }
  545. public function getIterator() {
  546. return new \ArrayIterator($this->_pool);
  547. }
  548. public function writeCommand(Command $command) {
  549. $this->getConnection($command)->writeCommand($command);
  550. }
  551. public function readResponse(Command $command) {
  552. return $this->getConnection($command)->readResponse($command);
  553. }
  554. }
  555. /* ------------------------------------------------------------------------- */
  556. abstract class RedisServerProfile {
  557. const DEFAULT_SERVER_PROFILE = '\Predis\RedisServer__V1_2';
  558. private $_registeredCommands;
  559. public function __construct() {
  560. $this->_registeredCommands = $this->getSupportedCommands();
  561. }
  562. public abstract function getVersion();
  563. protected abstract function getSupportedCommands();
  564. public static function getDefault() {
  565. $defaultProfile = self::DEFAULT_SERVER_PROFILE;
  566. return new $defaultProfile();
  567. }
  568. public function createCommand($method, $arguments = array()) {
  569. $commandClass = $this->_registeredCommands[$method];
  570. if ($commandClass === null) {
  571. throw new ClientException("'$method' is not a registered Redis command");
  572. }
  573. $command = new $commandClass();
  574. $command->setArgumentsArray($arguments);
  575. return $command;
  576. }
  577. public function registerCommands(Array $commands) {
  578. foreach ($commands as $command => $aliases) {
  579. $this->registerCommand($command, $aliases);
  580. }
  581. }
  582. public function registerCommand($command, $aliases) {
  583. $commandReflection = new \ReflectionClass($command);
  584. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  585. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  586. }
  587. if (is_array($aliases)) {
  588. foreach ($aliases as $alias) {
  589. $this->_registeredCommands[$alias] = $command;
  590. }
  591. }
  592. else {
  593. $this->_registeredCommands[$aliases] = $command;
  594. }
  595. }
  596. }
  597. class RedisServer__V1_0 extends RedisServerProfile {
  598. public function getVersion() { return 1.0; }
  599. public function getSupportedCommands() {
  600. return array(
  601. /* miscellaneous commands */
  602. 'ping' => '\Predis\Commands\Ping',
  603. 'echo' => '\Predis\Commands\DoEcho',
  604. 'auth' => '\Predis\Commands\Auth',
  605. /* connection handling */
  606. 'quit' => '\Predis\Commands\Quit',
  607. /* commands operating on string values */
  608. 'set' => '\Predis\Commands\Set',
  609. 'setnx' => '\Predis\Commands\SetPreserve',
  610. 'setPreserve' => '\Predis\Commands\SetPreserve',
  611. 'get' => '\Predis\Commands\Get',
  612. 'mget' => '\Predis\Commands\GetMultiple',
  613. 'getMultiple' => '\Predis\Commands\GetMultiple',
  614. 'getset' => '\Predis\Commands\GetSet',
  615. 'getSet' => '\Predis\Commands\GetSet',
  616. 'incr' => '\Predis\Commands\Increment',
  617. 'increment' => '\Predis\Commands\Increment',
  618. 'incrby' => '\Predis\Commands\IncrementBy',
  619. 'incrementBy' => '\Predis\Commands\IncrementBy',
  620. 'decr' => '\Predis\Commands\Decrement',
  621. 'decrement' => '\Predis\Commands\Decrement',
  622. 'decrby' => '\Predis\Commands\DecrementBy',
  623. 'decrementBy' => '\Predis\Commands\DecrementBy',
  624. 'exists' => '\Predis\Commands\Exists',
  625. 'del' => '\Predis\Commands\Delete',
  626. 'delete' => '\Predis\Commands\Delete',
  627. 'type' => '\Predis\Commands\Type',
  628. /* commands operating on the key space */
  629. 'keys' => '\Predis\Commands\Keys',
  630. 'randomkey' => '\Predis\Commands\RandomKey',
  631. 'randomKey' => '\Predis\Commands\RandomKey',
  632. 'rename' => '\Predis\Commands\Rename',
  633. 'renamenx' => '\Predis\Commands\RenamePreserve',
  634. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  635. 'expire' => '\Predis\Commands\Expire',
  636. 'expireat' => '\Predis\Commands\ExpireAt',
  637. 'expireAt' => '\Predis\Commands\ExpireAt',
  638. 'dbsize' => '\Predis\Commands\DatabaseSize',
  639. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  640. 'ttl' => '\Predis\Commands\TimeToLive',
  641. 'timeToLive' => '\Predis\Commands\TimeToLive',
  642. /* commands operating on lists */
  643. 'rpush' => '\Predis\Commands\ListPushTail',
  644. 'pushTail' => '\Predis\Commands\ListPushTail',
  645. 'lpush' => '\Predis\Commands\ListPushHead',
  646. 'pushHead' => '\Predis\Commands\ListPushHead',
  647. 'llen' => '\Predis\Commands\ListLength',
  648. 'listLength' => '\Predis\Commands\ListLength',
  649. 'lrange' => '\Predis\Commands\ListRange',
  650. 'listRange' => '\Predis\Commands\ListRange',
  651. 'ltrim' => '\Predis\Commands\ListTrim',
  652. 'listTrim' => '\Predis\Commands\ListTrim',
  653. 'lindex' => '\Predis\Commands\ListIndex',
  654. 'listIndex' => '\Predis\Commands\ListIndex',
  655. 'lset' => '\Predis\Commands\ListSet',
  656. 'listSet' => '\Predis\Commands\ListSet',
  657. 'lrem' => '\Predis\Commands\ListRemove',
  658. 'listRemove' => '\Predis\Commands\ListRemove',
  659. 'lpop' => '\Predis\Commands\ListPopFirst',
  660. 'popFirst' => '\Predis\Commands\ListPopFirst',
  661. 'rpop' => '\Predis\Commands\ListPopLast',
  662. 'popLast' => '\Predis\Commands\ListPopLast',
  663. /* commands operating on sets */
  664. 'sadd' => '\Predis\Commands\SetAdd',
  665. 'setAdd' => '\Predis\Commands\SetAdd',
  666. 'srem' => '\Predis\Commands\SetRemove',
  667. 'setRemove' => '\Predis\Commands\SetRemove',
  668. 'spop' => '\Predis\Commands\SetPop',
  669. 'setPop' => '\Predis\Commands\SetPop',
  670. 'smove' => '\Predis\Commands\SetMove',
  671. 'setMove' => '\Predis\Commands\SetMove',
  672. 'scard' => '\Predis\Commands\SetCardinality',
  673. 'setCardinality' => '\Predis\Commands\SetCardinality',
  674. 'sismember' => '\Predis\Commands\SetIsMember',
  675. 'setIsMember' => '\Predis\Commands\SetIsMember',
  676. 'sinter' => '\Predis\Commands\SetIntersection',
  677. 'setIntersection' => '\Predis\Commands\SetIntersection',
  678. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  679. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  680. 'sunion' => '\Predis\Commands\SetUnion',
  681. 'setUnion' => '\Predis\Commands\SetUnion',
  682. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  683. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  684. 'sdiff' => '\Predis\Commands\SetDifference',
  685. 'setDifference' => '\Predis\Commands\SetDifference',
  686. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  687. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  688. 'smembers' => '\Predis\Commands\SetMembers',
  689. 'setMembers' => '\Predis\Commands\SetMembers',
  690. 'srandmember' => '\Predis\Commands\SetRandomMember',
  691. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  692. /* multiple databases handling commands */
  693. 'select' => '\Predis\Commands\SelectDatabase',
  694. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  695. 'move' => '\Predis\Commands\MoveKey',
  696. 'moveKey' => '\Predis\Commands\MoveKey',
  697. 'flushdb' => '\Predis\Commands\FlushDatabase',
  698. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  699. 'flushall' => '\Predis\Commands\FlushAll',
  700. 'flushDatabases' => '\Predis\Commands\FlushAll',
  701. /* sorting */
  702. 'sort' => '\Predis\Commands\Sort',
  703. /* remote server control commands */
  704. 'info' => '\Predis\Commands\Info',
  705. 'slaveof' => '\Predis\Commands\SlaveOf',
  706. 'slaveOf' => '\Predis\Commands\SlaveOf',
  707. /* persistence control commands */
  708. 'save' => '\Predis\Commands\Save',
  709. 'bgsave' => '\Predis\Commands\BackgroundSave',
  710. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  711. 'lastsave' => '\Predis\Commands\LastSave',
  712. 'lastSave' => '\Predis\Commands\LastSave',
  713. 'shutdown' => '\Predis\Commands\Shutdown'
  714. );
  715. }
  716. }
  717. class RedisServer__V1_2 extends RedisServer__V1_0 {
  718. public function getVersion() { return 1.2; }
  719. public function getSupportedCommands() {
  720. return array_merge(parent::getSupportedCommands(), array(
  721. /* commands operating on string values */
  722. 'mset' => '\Predis\Commands\SetMultiple',
  723. 'setMultiple' => '\Predis\Commands\SetMultiple',
  724. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  725. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  726. /* commands operating on lists */
  727. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  728. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  729. /* commands operating on sorted sets */
  730. 'zadd' => '\Predis\Commands\ZSetAdd',
  731. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  732. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  733. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  734. 'zrem' => '\Predis\Commands\ZSetRemove',
  735. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  736. 'zrange' => '\Predis\Commands\ZSetRange',
  737. 'zsetRange' => '\Predis\Commands\ZSetRange',
  738. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  739. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  740. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  741. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  742. 'zcard' => '\Predis\Commands\ZSetCardinality',
  743. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  744. 'zscore' => '\Predis\Commands\ZSetScore',
  745. 'zsetScore' => '\Predis\Commands\ZSetScore',
  746. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  747. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore'
  748. ));
  749. }
  750. }
  751. /* ------------------------------------------------------------------------- */
  752. namespace Predis\Utilities;
  753. class HashRing {
  754. const DEFAULT_REPLICAS = 128;
  755. private $_ring, $_ringKeys, $_replicas;
  756. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  757. $this->_replicas = $replicas;
  758. $this->_ring = array();
  759. $this->_ringKeys = array();
  760. }
  761. public function add($node) {
  762. $nodeHash = (string) $node;
  763. $replicas = $this->_replicas;
  764. for ($i = 0; $i < $replicas; $i++) {
  765. $key = crc32($nodeHash . ':' . $i);
  766. $this->_ring[$key] = $node;
  767. }
  768. ksort($this->_ring, SORT_NUMERIC);
  769. $this->_ringKeys = array_keys($this->_ring);
  770. }
  771. public function remove($node) {
  772. $nodeHash = (string) $node;
  773. $replicas = $this->_replicas;
  774. for ($i = 0; $i < $replicas; $i++) {
  775. $key = crc32($nodeHash . ':' . $i);
  776. unset($this->_ring[$key]);
  777. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  778. return $rk !== $key;
  779. });
  780. }
  781. }
  782. public function get($key) {
  783. return $this->_ring[$this->getNodeKey($key)];
  784. }
  785. private function getNodeKey($key) {
  786. $ringKeys = $this->_ringKeys;
  787. $upper = count($ringKeys) - 1;
  788. $lower = 0;
  789. $index = 0;
  790. while ($lower <= $upper) {
  791. $index = ($lower + $upper) / 2;
  792. $item = $ringKeys[$index];
  793. if ($item > $key) {
  794. $upper = $index - 1;
  795. }
  796. else if ($item < $key) {
  797. $lower = $index + 1;
  798. }
  799. else {
  800. return $index;
  801. }
  802. }
  803. return $ringKeys[$upper];
  804. }
  805. }
  806. /* ------------------------------------------------------------------------- */
  807. namespace Predis\Commands;
  808. /* miscellaneous commands */
  809. class Ping extends \Predis\InlineCommand {
  810. public function canBeHashed() { return false; }
  811. public function getCommandId() { return 'PING'; }
  812. public function parseResponse($data) {
  813. return $data === 'PONG' ? true : false;
  814. }
  815. }
  816. class DoEcho extends \Predis\BulkCommand {
  817. public function canBeHashed() { return false; }
  818. public function getCommandId() { return 'ECHO'; }
  819. }
  820. class Auth extends \Predis\InlineCommand {
  821. public function canBeHashed() { return false; }
  822. public function getCommandId() { return 'AUTH'; }
  823. }
  824. /* connection handling */
  825. class Quit extends \Predis\InlineCommand {
  826. public function canBeHashed() { return false; }
  827. public function getCommandId() { return 'QUIT'; }
  828. public function closesConnection() { return true; }
  829. }
  830. /* commands operating on string values */
  831. class Set extends \Predis\BulkCommand {
  832. public function getCommandId() { return 'SET'; }
  833. }
  834. class SetPreserve extends \Predis\BulkCommand {
  835. public function getCommandId() { return 'SETNX'; }
  836. public function parseResponse($data) { return (bool) $data; }
  837. }
  838. class SetMultiple extends \Predis\MultiBulkCommand {
  839. public function canBeHashed() { return false; }
  840. public function getCommandId() { return 'MSET'; }
  841. }
  842. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  843. public function canBeHashed() { return false; }
  844. public function getCommandId() { return 'MSETNX'; }
  845. public function parseResponse($data) { return (bool) $data; }
  846. }
  847. class Get extends \Predis\InlineCommand {
  848. public function getCommandId() { return 'GET'; }
  849. }
  850. class GetMultiple extends \Predis\InlineCommand {
  851. public function canBeHashed() { return false; }
  852. public function getCommandId() { return 'MGET'; }
  853. }
  854. class GetSet extends \Predis\BulkCommand {
  855. public function getCommandId() { return 'GETSET'; }
  856. }
  857. class Increment extends \Predis\InlineCommand {
  858. public function getCommandId() { return 'INCR'; }
  859. }
  860. class IncrementBy extends \Predis\InlineCommand {
  861. public function getCommandId() { return 'INCRBY'; }
  862. }
  863. class Decrement extends \Predis\InlineCommand {
  864. public function getCommandId() { return 'DECR'; }
  865. }
  866. class DecrementBy extends \Predis\InlineCommand {
  867. public function getCommandId() { return 'DECRBY'; }
  868. }
  869. class Exists extends \Predis\InlineCommand {
  870. public function getCommandId() { return 'EXISTS'; }
  871. public function parseResponse($data) { return (bool) $data; }
  872. }
  873. class Delete extends \Predis\InlineCommand {
  874. public function getCommandId() { return 'DEL'; }
  875. public function parseResponse($data) { return (bool) $data; }
  876. }
  877. class Type extends \Predis\InlineCommand {
  878. public function getCommandId() { return 'TYPE'; }
  879. }
  880. /* commands operating on the key space */
  881. class Keys extends \Predis\InlineCommand {
  882. public function canBeHashed() { return false; }
  883. public function getCommandId() { return 'KEYS'; }
  884. public function parseResponse($data) {
  885. // TODO: is this behaviour correct?
  886. return strlen($data) > 0 ? explode(' ', $data) : array();
  887. }
  888. }
  889. class RandomKey extends \Predis\InlineCommand {
  890. public function canBeHashed() { return false; }
  891. public function getCommandId() { return 'RANDOMKEY'; }
  892. public function parseResponse($data) { return $data !== '' ? $data : null; }
  893. }
  894. class Rename extends \Predis\InlineCommand {
  895. // TODO: doesn't RENAME break the hash-based client-side sharding?
  896. public function canBeHashed() { return false; }
  897. public function getCommandId() { return 'RENAME'; }
  898. }
  899. class RenamePreserve extends \Predis\InlineCommand {
  900. public function canBeHashed() { return false; }
  901. public function getCommandId() { return 'RENAMENX'; }
  902. public function parseResponse($data) { return (bool) $data; }
  903. }
  904. class Expire extends \Predis\InlineCommand {
  905. public function getCommandId() { return 'EXPIRE'; }
  906. public function parseResponse($data) { return (bool) $data; }
  907. }
  908. class ExpireAt extends \Predis\InlineCommand {
  909. public function getCommandId() { return 'EXPIREAT'; }
  910. public function parseResponse($data) { return (bool) $data; }
  911. }
  912. class DatabaseSize extends \Predis\InlineCommand {
  913. public function canBeHashed() { return false; }
  914. public function getCommandId() { return 'DBSIZE'; }
  915. }
  916. class TimeToLive extends \Predis\InlineCommand {
  917. public function getCommandId() { return 'TTL'; }
  918. }
  919. /* commands operating on lists */
  920. class ListPushTail extends \Predis\BulkCommand {
  921. public function getCommandId() { return 'RPUSH'; }
  922. }
  923. class ListPushHead extends \Predis\BulkCommand {
  924. public function getCommandId() { return 'LPUSH'; }
  925. }
  926. class ListLength extends \Predis\InlineCommand {
  927. public function getCommandId() { return 'LLEN'; }
  928. }
  929. class ListRange extends \Predis\InlineCommand {
  930. public function getCommandId() { return 'LRANGE'; }
  931. }
  932. class ListTrim extends \Predis\InlineCommand {
  933. public function getCommandId() { return 'LTRIM'; }
  934. }
  935. class ListIndex extends \Predis\InlineCommand {
  936. public function getCommandId() { return 'LINDEX'; }
  937. }
  938. class ListSet extends \Predis\BulkCommand {
  939. public function getCommandId() { return 'LSET'; }
  940. }
  941. class ListRemove extends \Predis\BulkCommand {
  942. public function getCommandId() { return 'LREM'; }
  943. }
  944. class ListPopLastPushHead extends \Predis\BulkCommand {
  945. public function getCommandId() { return 'RPOPLPUSH'; }
  946. }
  947. class ListPopFirst extends \Predis\InlineCommand {
  948. public function getCommandId() { return 'LPOP'; }
  949. }
  950. class ListPopLast extends \Predis\InlineCommand {
  951. public function getCommandId() { return 'RPOP'; }
  952. }
  953. /* commands operating on sets */
  954. class SetAdd extends \Predis\BulkCommand {
  955. public function getCommandId() { return 'SADD'; }
  956. public function parseResponse($data) { return (bool) $data; }
  957. }
  958. class SetRemove extends \Predis\BulkCommand {
  959. public function getCommandId() { return 'SREM'; }
  960. public function parseResponse($data) { return (bool) $data; }
  961. }
  962. class SetPop extends \Predis\InlineCommand {
  963. public function getCommandId() { return 'SPOP'; }
  964. }
  965. class SetMove extends \Predis\BulkCommand {
  966. public function canBeHashed() { return false; }
  967. public function getCommandId() { return 'SMOVE'; }
  968. public function parseResponse($data) { return (bool) $data; }
  969. }
  970. class SetCardinality extends \Predis\InlineCommand {
  971. public function getCommandId() { return 'SCARD'; }
  972. }
  973. class SetIsMember extends \Predis\BulkCommand {
  974. public function getCommandId() { return 'SISMEMBER'; }
  975. public function parseResponse($data) { return (bool) $data; }
  976. }
  977. class SetIntersection extends \Predis\InlineCommand {
  978. public function getCommandId() { return 'SINTER'; }
  979. }
  980. class SetIntersectionStore extends \Predis\InlineCommand {
  981. public function getCommandId() { return 'SINTERSTORE'; }
  982. }
  983. class SetUnion extends \Predis\InlineCommand {
  984. public function getCommandId() { return 'SUNION'; }
  985. }
  986. class SetUnionStore extends \Predis\InlineCommand {
  987. public function getCommandId() { return 'SUNIONSTORE'; }
  988. }
  989. class SetDifference extends \Predis\InlineCommand {
  990. public function getCommandId() { return 'SDIFF'; }
  991. }
  992. class SetDifferenceStore extends \Predis\InlineCommand {
  993. public function getCommandId() { return 'SDIFFSTORE'; }
  994. }
  995. class SetMembers extends \Predis\InlineCommand {
  996. public function getCommandId() { return 'SMEMBERS'; }
  997. }
  998. class SetRandomMember extends \Predis\InlineCommand {
  999. public function getCommandId() { return 'SRANDMEMBER'; }
  1000. }
  1001. /* commands operating on sorted sets */
  1002. class ZSetAdd extends \Predis\BulkCommand {
  1003. public function getCommandId() { return 'ZADD'; }
  1004. public function parseResponse($data) { return (bool) $data; }
  1005. }
  1006. class ZSetIncrementBy extends \Predis\BulkCommand {
  1007. public function getCommandId() { return 'ZINCRBY'; }
  1008. }
  1009. class ZSetRemove extends \Predis\BulkCommand {
  1010. public function getCommandId() { return 'ZREM'; }
  1011. public function parseResponse($data) { return (bool) $data; }
  1012. }
  1013. class ZSetRange extends \Predis\InlineCommand {
  1014. public function getCommandId() { return 'ZRANGE'; }
  1015. public function parseResponse($data) {
  1016. $arguments = $this->getArguments();
  1017. if (count($arguments) === 4) {
  1018. if (strtolower($arguments[3]) === 'withscores') {
  1019. $result = array();
  1020. for ($i = 0; $i < count($data); $i++) {
  1021. $result[] = array($data[$i], $data[++$i]);
  1022. }
  1023. return $result;
  1024. }
  1025. }
  1026. return $data;
  1027. }
  1028. }
  1029. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1030. public function getCommandId() { return 'ZREVRANGE'; }
  1031. }
  1032. class ZSetRangeByScore extends \Predis\InlineCommand {
  1033. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1034. }
  1035. class ZSetCardinality extends \Predis\InlineCommand {
  1036. public function getCommandId() { return 'ZCARD'; }
  1037. }
  1038. class ZSetScore extends \Predis\BulkCommand {
  1039. public function getCommandId() { return 'ZSCORE'; }
  1040. }
  1041. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1042. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1043. }
  1044. /* multiple databases handling commands */
  1045. class SelectDatabase extends \Predis\InlineCommand {
  1046. public function canBeHashed() { return false; }
  1047. public function getCommandId() { return 'SELECT'; }
  1048. }
  1049. class MoveKey extends \Predis\InlineCommand {
  1050. public function canBeHashed() { return false; }
  1051. public function getCommandId() { return 'MOVE'; }
  1052. public function parseResponse($data) { return (bool) $data; }
  1053. }
  1054. class FlushDatabase extends \Predis\InlineCommand {
  1055. public function canBeHashed() { return false; }
  1056. public function getCommandId() { return 'FLUSHDB'; }
  1057. }
  1058. class FlushAll extends \Predis\InlineCommand {
  1059. public function canBeHashed() { return false; }
  1060. public function getCommandId() { return 'FLUSHALL'; }
  1061. }
  1062. /* sorting */
  1063. class Sort extends \Predis\InlineCommand {
  1064. public function getCommandId() { return 'SORT'; }
  1065. public function filterArguments(Array $arguments) {
  1066. if (count($arguments) === 1) {
  1067. return $arguments;
  1068. }
  1069. // TODO: add more parameters checks
  1070. $query = array($arguments[0]);
  1071. $sortParams = $arguments[1];
  1072. if (isset($sortParams['by'])) {
  1073. $query[] = 'BY ' . $sortParams['by'];
  1074. }
  1075. if (isset($sortParams['get'])) {
  1076. $query[] = 'GET ' . $sortParams['get'];
  1077. }
  1078. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1079. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1080. }
  1081. if (isset($sortParams['sort'])) {
  1082. $query[] = strtoupper($sortParams['sort']);
  1083. }
  1084. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1085. $query[] = 'ALPHA';
  1086. }
  1087. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1088. $query[] = 'STORE ' . $sortParams['store'];
  1089. }
  1090. return $query;
  1091. }
  1092. }
  1093. /* persistence control commands */
  1094. class Save extends \Predis\InlineCommand {
  1095. public function canBeHashed() { return false; }
  1096. public function getCommandId() { return 'SAVE'; }
  1097. }
  1098. class BackgroundSave extends \Predis\InlineCommand {
  1099. public function canBeHashed() { return false; }
  1100. public function getCommandId() { return 'BGSAVE'; }
  1101. }
  1102. class LastSave extends \Predis\InlineCommand {
  1103. public function canBeHashed() { return false; }
  1104. public function getCommandId() { return 'LASTSAVE'; }
  1105. }
  1106. class Shutdown extends \Predis\InlineCommand {
  1107. public function canBeHashed() { return false; }
  1108. public function getCommandId() { return 'SHUTDOWN'; }
  1109. public function closesConnection() { return true; }
  1110. }
  1111. /* remote server control commands */
  1112. class Info extends \Predis\InlineCommand {
  1113. public function canBeHashed() { return false; }
  1114. public function getCommandId() { return 'INFO'; }
  1115. public function parseResponse($data) {
  1116. $info = array();
  1117. $infoLines = explode("\r\n", $data, -1);
  1118. foreach ($infoLines as $row) {
  1119. list($k, $v) = explode(':', $row);
  1120. if (!preg_match('/^db\d+$/', $k)) {
  1121. $info[$k] = $v;
  1122. }
  1123. else {
  1124. $db = array();
  1125. foreach (explode(',', $v) as $dbvar) {
  1126. list($dbvk, $dbvv) = explode('=', $dbvar);
  1127. $db[trim($dbvk)] = $dbvv;
  1128. }
  1129. $info[$k] = $db;
  1130. }
  1131. }
  1132. return $info;
  1133. }
  1134. }
  1135. class SlaveOf extends \Predis\InlineCommand {
  1136. public function canBeHashed() { return false; }
  1137. public function getCommandId() { return 'SLAVEOF'; }
  1138. public function filterArguments(Array $arguments) {
  1139. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1140. }
  1141. }
  1142. ?>