Predis.php 47 KB

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