Predis.php 50 KB

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