Predis.php 51 KB

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