Predis.php 48 KB

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