Predis.php 50 KB

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