Predis.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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]) && is_array($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->createCommandInstance(
  57. 'auth', array($params->password)
  58. ));
  59. }
  60. if ($params->database !== null) {
  61. $connection->pushInitCommand($this->createCommandInstance(
  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->createCommandInstance($method, $arguments);
  87. return $this->executeCommand($command);
  88. }
  89. public function createCommandInstance($method, $arguments = array()) {
  90. return $this->_serverProfile->createCommandInstance($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. // TODO: I just have a doubt here...
  256. fread($socket, 2);
  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->createCommandInstance($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 createCommandInstance($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. /* ------------------------------------------------------------------------- */
  739. namespace Predis\Utilities;
  740. class HashRing {
  741. const DEFAULT_REPLICAS = 128;
  742. private $_ring, $_ringKeys, $_replicas;
  743. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  744. $this->_replicas = $replicas;
  745. $this->_ring = array();
  746. $this->_ringKeys = array();
  747. }
  748. public function add($node) {
  749. $nodeHash = (string) $node;
  750. $replicas = $this->_replicas;
  751. for ($i = 0; $i < $replicas; $i++) {
  752. $key = crc32($nodeHash . ':' . $i);
  753. $this->_ring[$key] = $node;
  754. }
  755. ksort($this->_ring, SORT_NUMERIC);
  756. $this->_ringKeys = array_keys($this->_ring);
  757. }
  758. public function remove($node) {
  759. $nodeHash = (string) $node;
  760. $replicas = $this->_replicas;
  761. for ($i = 0; $i < $replicas; $i++) {
  762. $key = crc32($nodeHash . ':' . $i);
  763. unset($this->_ring[$key]);
  764. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  765. return $rk !== $key;
  766. });
  767. }
  768. }
  769. public function get($key) {
  770. return $this->_ring[$this->getNodeKey($key)];
  771. }
  772. private function getNodeKey($key) {
  773. $ringKeys = $this->_ringKeys;
  774. $upper = count($ringKeys) - 1;
  775. $lower = 0;
  776. $index = 0;
  777. while ($lower <= $upper) {
  778. $index = ($lower + $upper) / 2;
  779. $item = $ringKeys[$index];
  780. if ($item > $key) {
  781. $upper = $index - 1;
  782. }
  783. else if ($item < $key) {
  784. $lower = $index + 1;
  785. }
  786. else {
  787. return $index;
  788. }
  789. }
  790. return $ringKeys[$upper];
  791. }
  792. }
  793. /* ------------------------------------------------------------------------- */
  794. namespace Predis\Commands;
  795. /* miscellaneous commands */
  796. class Ping extends \Predis\InlineCommand {
  797. public function canBeHashed() { return false; }
  798. public function getCommandId() { return 'PING'; }
  799. public function parseResponse($data) {
  800. return $data === 'PONG' ? true : false;
  801. }
  802. }
  803. class DoEcho extends \Predis\BulkCommand {
  804. public function canBeHashed() { return false; }
  805. public function getCommandId() { return 'ECHO'; }
  806. }
  807. class Auth extends \Predis\InlineCommand {
  808. public function canBeHashed() { return false; }
  809. public function getCommandId() { return 'AUTH'; }
  810. }
  811. /* connection handling */
  812. class Quit extends \Predis\InlineCommand {
  813. public function canBeHashed() { return false; }
  814. public function getCommandId() { return 'QUIT'; }
  815. public function closesConnection() { return true; }
  816. }
  817. /* commands operating on string values */
  818. class Set extends \Predis\BulkCommand {
  819. public function getCommandId() { return 'SET'; }
  820. }
  821. class SetPreserve extends \Predis\BulkCommand {
  822. public function getCommandId() { return 'SETNX'; }
  823. public function parseResponse($data) { return (bool) $data; }
  824. }
  825. class SetMultiple extends \Predis\MultiBulkCommand {
  826. public function canBeHashed() { return false; }
  827. public function getCommandId() { return 'MSET'; }
  828. }
  829. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  830. public function canBeHashed() { return false; }
  831. public function getCommandId() { return 'MSETNX'; }
  832. public function parseResponse($data) { return (bool) $data; }
  833. }
  834. class Get extends \Predis\InlineCommand {
  835. public function getCommandId() { return 'GET'; }
  836. }
  837. class GetMultiple extends \Predis\InlineCommand {
  838. public function canBeHashed() { return false; }
  839. public function getCommandId() { return 'MGET'; }
  840. }
  841. class GetSet extends \Predis\BulkCommand {
  842. public function getCommandId() { return 'GETSET'; }
  843. }
  844. class Increment extends \Predis\InlineCommand {
  845. public function getCommandId() { return 'INCR'; }
  846. }
  847. class IncrementBy extends \Predis\InlineCommand {
  848. public function getCommandId() { return 'INCRBY'; }
  849. }
  850. class Decrement extends \Predis\InlineCommand {
  851. public function getCommandId() { return 'DECR'; }
  852. }
  853. class DecrementBy extends \Predis\InlineCommand {
  854. public function getCommandId() { return 'DECRBY'; }
  855. }
  856. class Exists extends \Predis\InlineCommand {
  857. public function getCommandId() { return 'EXISTS'; }
  858. public function parseResponse($data) { return (bool) $data; }
  859. }
  860. class Delete extends \Predis\InlineCommand {
  861. public function getCommandId() { return 'DEL'; }
  862. public function parseResponse($data) { return (bool) $data; }
  863. }
  864. class Type extends \Predis\InlineCommand {
  865. public function getCommandId() { return 'TYPE'; }
  866. }
  867. /* commands operating on the key space */
  868. class Keys extends \Predis\InlineCommand {
  869. public function canBeHashed() { return false; }
  870. public function getCommandId() { return 'KEYS'; }
  871. public function parseResponse($data) {
  872. // TODO: is this behaviour correct?
  873. return strlen($data) > 0 ? explode(' ', $data) : array();
  874. }
  875. }
  876. class RandomKey extends \Predis\InlineCommand {
  877. public function canBeHashed() { return false; }
  878. public function getCommandId() { return 'RANDOMKEY'; }
  879. public function parseResponse($data) { return $data !== '' ? $data : null; }
  880. }
  881. class Rename extends \Predis\InlineCommand {
  882. // TODO: doesn't RENAME break the hash-based client-side sharding?
  883. public function canBeHashed() { return false; }
  884. public function getCommandId() { return 'RENAME'; }
  885. }
  886. class RenamePreserve extends \Predis\InlineCommand {
  887. public function canBeHashed() { return false; }
  888. public function getCommandId() { return 'RENAMENX'; }
  889. public function parseResponse($data) { return (bool) $data; }
  890. }
  891. class Expire extends \Predis\InlineCommand {
  892. public function getCommandId() { return 'EXPIRE'; }
  893. public function parseResponse($data) { return (bool) $data; }
  894. }
  895. class ExpireAt extends \Predis\InlineCommand {
  896. public function getCommandId() { return 'EXPIREAT'; }
  897. public function parseResponse($data) { return (bool) $data; }
  898. }
  899. class DatabaseSize extends \Predis\InlineCommand {
  900. public function canBeHashed() { return false; }
  901. public function getCommandId() { return 'DBSIZE'; }
  902. }
  903. class TimeToLive extends \Predis\InlineCommand {
  904. public function getCommandId() { return 'TTL'; }
  905. }
  906. /* commands operating on lists */
  907. class ListPushTail extends \Predis\BulkCommand {
  908. public function getCommandId() { return 'RPUSH'; }
  909. }
  910. class ListPushHead extends \Predis\BulkCommand {
  911. public function getCommandId() { return 'LPUSH'; }
  912. }
  913. class ListLength extends \Predis\InlineCommand {
  914. public function getCommandId() { return 'LLEN'; }
  915. }
  916. class ListRange extends \Predis\InlineCommand {
  917. public function getCommandId() { return 'LRANGE'; }
  918. }
  919. class ListTrim extends \Predis\InlineCommand {
  920. public function getCommandId() { return 'LTRIM'; }
  921. }
  922. class ListIndex extends \Predis\InlineCommand {
  923. public function getCommandId() { return 'LINDEX'; }
  924. }
  925. class ListSet extends \Predis\BulkCommand {
  926. public function getCommandId() { return 'LSET'; }
  927. }
  928. class ListRemove extends \Predis\BulkCommand {
  929. public function getCommandId() { return 'LREM'; }
  930. }
  931. class ListPopLastPushHead extends \Predis\BulkCommand {
  932. public function getCommandId() { return 'RPOPLPUSH'; }
  933. }
  934. class ListPopFirst extends \Predis\InlineCommand {
  935. public function getCommandId() { return 'LPOP'; }
  936. }
  937. class ListPopLast extends \Predis\InlineCommand {
  938. public function getCommandId() { return 'RPOP'; }
  939. }
  940. /* commands operating on sets */
  941. class SetAdd extends \Predis\BulkCommand {
  942. public function getCommandId() { return 'SADD'; }
  943. public function parseResponse($data) { return (bool) $data; }
  944. }
  945. class SetRemove extends \Predis\BulkCommand {
  946. public function getCommandId() { return 'SREM'; }
  947. public function parseResponse($data) { return (bool) $data; }
  948. }
  949. class SetPop extends \Predis\InlineCommand {
  950. public function getCommandId() { return 'SPOP'; }
  951. }
  952. class SetMove extends \Predis\BulkCommand {
  953. public function canBeHashed() { return false; }
  954. public function getCommandId() { return 'SMOVE'; }
  955. public function parseResponse($data) { return (bool) $data; }
  956. }
  957. class SetCardinality extends \Predis\InlineCommand {
  958. public function getCommandId() { return 'SCARD'; }
  959. }
  960. class SetIsMember extends \Predis\BulkCommand {
  961. public function getCommandId() { return 'SISMEMBER'; }
  962. public function parseResponse($data) { return (bool) $data; }
  963. }
  964. class SetIntersection extends \Predis\InlineCommand {
  965. public function getCommandId() { return 'SINTER'; }
  966. }
  967. class SetIntersectionStore extends \Predis\InlineCommand {
  968. public function getCommandId() { return 'SINTERSTORE'; }
  969. }
  970. class SetUnion extends \Predis\InlineCommand {
  971. public function getCommandId() { return 'SUNION'; }
  972. }
  973. class SetUnionStore extends \Predis\InlineCommand {
  974. public function getCommandId() { return 'SUNIONSTORE'; }
  975. }
  976. class SetDifference extends \Predis\InlineCommand {
  977. public function getCommandId() { return 'SDIFF'; }
  978. }
  979. class SetDifferenceStore extends \Predis\InlineCommand {
  980. public function getCommandId() { return 'SDIFFSTORE'; }
  981. }
  982. class SetMembers extends \Predis\InlineCommand {
  983. public function getCommandId() { return 'SMEMBERS'; }
  984. }
  985. class SetRandomMember extends \Predis\InlineCommand {
  986. public function getCommandId() { return 'SRANDMEMBER'; }
  987. }
  988. /* commands operating on sorted sets */
  989. class ZSetAdd extends \Predis\BulkCommand {
  990. public function getCommandId() { return 'ZADD'; }
  991. public function parseResponse($data) { return (bool) $data; }
  992. }
  993. class ZSetIncrementBy extends \Predis\BulkCommand {
  994. public function getCommandId() { return 'ZINCRBY'; }
  995. }
  996. class ZSetRemove extends \Predis\BulkCommand {
  997. public function getCommandId() { return 'ZREM'; }
  998. public function parseResponse($data) { return (bool) $data; }
  999. }
  1000. class ZSetRange extends \Predis\InlineCommand {
  1001. public function getCommandId() { return 'ZRANGE'; }
  1002. public function parseResponse($data) {
  1003. $arguments = $this->getArguments();
  1004. if (count($arguments) === 4) {
  1005. if (strtolower($arguments[3]) === 'withscores') {
  1006. $result = array();
  1007. for ($i = 0; $i < count($data); $i++) {
  1008. $result[] = array($data[$i], $data[++$i]);
  1009. }
  1010. return $result;
  1011. }
  1012. }
  1013. return $data;
  1014. }
  1015. }
  1016. class ZSetReverseRange extends \Predis\InlineCommand {
  1017. public function getCommandId() { return 'ZREVRANGE'; }
  1018. public function parseResponse($data) {
  1019. $arguments = $this->getArguments();
  1020. if (count($arguments) === 4) {
  1021. if (strtolower($arguments[3]) === 'withscores') {
  1022. $result = array();
  1023. for ($i = 0; $i < count($data); $i++) {
  1024. $result[] = array($data[$i], $data[++$i]);
  1025. }
  1026. return $result;
  1027. }
  1028. }
  1029. return $data;
  1030. }
  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($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($arguments) {
  1139. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1140. }
  1141. }
  1142. ?>