Predis.php 51 KB

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