Predis.php 47 KB

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