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