Predis.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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, $_responseReader;
  10. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  11. $this->_responseReader = new ResponseReader();
  12. $this->setProfile($serverProfile ?: RedisServerProfile::getDefault());
  13. $this->setupConnection($parameters);
  14. }
  15. public function __destruct() {
  16. $this->_connection->disconnect();
  17. }
  18. public static function create(/* arguments */) {
  19. $argv = func_get_args();
  20. $argc = func_num_args();
  21. $serverProfile = null;
  22. $lastArg = $argv[$argc-1];
  23. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  24. $serverProfile = array_pop($argv);
  25. $argc--;
  26. }
  27. if ($argc === 0) {
  28. throw new ClientException('Missing connection parameters');
  29. }
  30. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  31. }
  32. private function setupConnection($parameters) {
  33. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  34. throw new ClientException('Invalid parameters type (array or string expected)');
  35. }
  36. if (is_array($parameters) && isset($parameters[0])) {
  37. $cluster = new ConnectionCluster();
  38. foreach ($parameters as $shardParams) {
  39. $cluster->add($this->createConnection($shardParams));
  40. }
  41. $this->setConnection($cluster);
  42. }
  43. else {
  44. $this->setConnection($this->createConnection($parameters));
  45. }
  46. }
  47. private function createConnection($parameters) {
  48. $params = new ConnectionParameters($parameters);
  49. $connection = new Connection($params, $this->_responseReader);
  50. if ($params->password !== null) {
  51. $connection->pushInitCommand($this->createCommand(
  52. 'auth', array($params->password)
  53. ));
  54. }
  55. if ($params->database !== null) {
  56. $connection->pushInitCommand($this->createCommand(
  57. 'select', array($params->database)
  58. ));
  59. }
  60. return $connection;
  61. }
  62. private function setConnection(IConnection $connection) {
  63. $this->_connection = $connection;
  64. }
  65. public function setProfile(RedisServerProfile $serverProfile) {
  66. $this->_serverProfile = $serverProfile;
  67. }
  68. public function getProfile() {
  69. return $this->_serverProfile;
  70. }
  71. public function getResponseReader() {
  72. return $this->_responseReader;
  73. }
  74. public function connect() {
  75. $this->_connection->connect();
  76. }
  77. public function disconnect() {
  78. $this->_connection->disconnect();
  79. }
  80. public function isConnected() {
  81. return $this->_connection->isConnected();
  82. }
  83. public function getConnection($id = null) {
  84. if (!isset($id)) {
  85. return $this->_connection;
  86. }
  87. else {
  88. return $this->_connection instanceof ConnectionCluster
  89. ? $this->_connection->getConnectionById($id)
  90. : $this->_connection;
  91. }
  92. }
  93. public function __call($method, $arguments) {
  94. $command = $this->_serverProfile->createCommand($method, $arguments);
  95. return $this->executeCommand($command);
  96. }
  97. public function createCommand($method, $arguments = array()) {
  98. return $this->_serverProfile->createCommand($method, $arguments);
  99. }
  100. private function executeCommandInternal(IConnection $connection, Command $command) {
  101. $connection->writeCommand($command);
  102. if ($command->closesConnection()) {
  103. return $connection->disconnect();
  104. }
  105. return $connection->readResponse($command);
  106. }
  107. public function executeCommand(Command $command) {
  108. return self::executeCommandInternal($this->_connection, $command);
  109. }
  110. public function executeCommandOnShards(Command $command) {
  111. $replies = array();
  112. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  113. foreach($this->_connection as $connection) {
  114. $replies[] = self::executeCommandInternal($connection, $command);
  115. }
  116. }
  117. else {
  118. $replies[] = self::executeCommandInternal($this->_connection, $command);
  119. }
  120. return $replies;
  121. }
  122. public function rawCommand($rawCommandData, $closesConnection = false) {
  123. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  124. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  125. }
  126. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  127. }
  128. public function pipeline($pipelineBlock = null) {
  129. $pipeline = new CommandPipeline($this);
  130. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  131. }
  132. public function multiExec($multiExecBlock = null) {
  133. $multiExec = new MultiExecBlock($this);
  134. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  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. // TODO: why getArguments is protected?
  177. return isset($this->_arguments) ? $this->_arguments : array();
  178. }
  179. public function getArgument($index = 0) {
  180. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  181. }
  182. public function parseResponse($data) {
  183. return $data;
  184. }
  185. public final function __invoke() {
  186. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  187. }
  188. }
  189. abstract class InlineCommand extends Command {
  190. public function serializeRequest($command, $arguments) {
  191. if (isset($arguments[0]) && is_array($arguments[0])) {
  192. $arguments[0] = implode($arguments[0], ' ');
  193. }
  194. return $command . ' ' . implode($arguments, ' ') . ResponseReader::NEWLINE;
  195. }
  196. }
  197. abstract class BulkCommand extends Command {
  198. public function serializeRequest($command, $arguments) {
  199. $data = array_pop($arguments);
  200. if (is_array($data)) {
  201. $data = implode($data, ' ');
  202. }
  203. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  204. ResponseReader::NEWLINE . $data . ResponseReader::NEWLINE;
  205. }
  206. }
  207. abstract class MultiBulkCommand extends Command {
  208. public function serializeRequest($command, $arguments) {
  209. $buffer = array();
  210. $cmd_args = null;
  211. if (count($arguments) === 1 && is_array($arguments[0])) {
  212. $cmd_args = array();
  213. foreach ($arguments[0] as $k => $v) {
  214. $cmd_args[] = $k;
  215. $cmd_args[] = $v;
  216. }
  217. }
  218. else {
  219. $cmd_args = $arguments;
  220. }
  221. $buffer[] = '*' . ((string) count($cmd_args) + 1) . ResponseReader::NEWLINE;
  222. $buffer[] = '$' . strlen($command) . ResponseReader::NEWLINE . $command . ResponseReader::NEWLINE;
  223. foreach ($cmd_args as $argument) {
  224. $buffer[] = '$' . strlen($argument) . ResponseReader::NEWLINE . $argument . ResponseReader::NEWLINE;
  225. }
  226. return implode('', $buffer);
  227. }
  228. }
  229. /* ------------------------------------------------------------------------- */
  230. interface IResponseHandler {
  231. function handle(Connection $connection, $payload);
  232. }
  233. class ResponseStatusHandler implements IResponseHandler {
  234. public function handle(Connection $connection, $status) {
  235. if ($status === ResponseReader::OK) {
  236. return true;
  237. }
  238. else if ($status === ResponseReader::QUEUED) {
  239. return new ResponseQueued();
  240. }
  241. return $status;
  242. }
  243. }
  244. class ResponseErrorHandler implements IResponseHandler {
  245. public function handle(Connection $connection, $errorMessage) {
  246. throw new ServerException(substr($errorMessage, 4));
  247. }
  248. }
  249. class ResponseErrorSilentHandler implements IResponseHandler {
  250. public function handle(Connection $connection, $errorMessage) {
  251. return new ResponseError(substr($errorMessage, 4));
  252. }
  253. }
  254. class ResponseBulkHandler implements IResponseHandler {
  255. public function handle(Connection $connection, $dataLength) {
  256. $socket = $connection->getSocket();
  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. if ($value === false) {
  263. throw new ClientException('An error has occurred while reading from the network stream');
  264. }
  265. fread($socket, 2);
  266. return $value;
  267. }
  268. else if ($dataLength == 0) {
  269. fread($socket, 2);
  270. return '';
  271. }
  272. return null;
  273. }
  274. }
  275. class ResponseMultiBulkHandler implements IResponseHandler {
  276. public function handle(Connection $connection, $rawLength) {
  277. if (!is_numeric($rawLength)) {
  278. throw new ClientException("Cannot parse '$rawLength' as data length");
  279. }
  280. $listLength = (int) $rawLength;
  281. if ($listLength === -1) {
  282. return null;
  283. }
  284. $list = array();
  285. if ($listLength > 0) {
  286. for ($i = 0; $i < $listLength; $i++) {
  287. $list[] = $connection->getResponseReader()->read($connection);
  288. }
  289. }
  290. return $list;
  291. }
  292. }
  293. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  294. public function handle(Connection $connection, $rawLength) {
  295. if (!is_numeric($rawLength)) {
  296. throw new ClientException("Cannot parse '$rawLength' as data length");
  297. }
  298. return new Utilities\MultiBulkResponseIterator($connection, (int)$rawLength);
  299. }
  300. }
  301. class ResponseIntegerHandler implements IResponseHandler {
  302. public function handle(Connection $connection, $number) {
  303. if (is_numeric($number)) {
  304. return (int) $number;
  305. }
  306. else {
  307. if ($number !== ResponseReader::NULL) {
  308. throw new ClientException("Cannot parse '$number' as numeric response");
  309. }
  310. return null;
  311. }
  312. }
  313. }
  314. class ResponseReader {
  315. const NEWLINE = "\r\n";
  316. const OK = 'OK';
  317. const ERROR = 'ERR';
  318. const QUEUED = 'QUEUED';
  319. const NULL = 'nil';
  320. const PREFIX_STATUS = '+';
  321. const PREFIX_ERROR = '-';
  322. const PREFIX_INTEGER = ':';
  323. const PREFIX_BULK = '$';
  324. const PREFIX_MULTI_BULK = '*';
  325. private $_prefixHandlers;
  326. public function __construct() {
  327. $this->initializePrefixHandlers();
  328. }
  329. private function initializePrefixHandlers() {
  330. $this->_prefixHandlers = array(
  331. self::PREFIX_STATUS => new ResponseStatusHandler(),
  332. self::PREFIX_ERROR => new ResponseErrorHandler(),
  333. self::PREFIX_INTEGER => new ResponseIntegerHandler(),
  334. self::PREFIX_BULK => new ResponseBulkHandler(),
  335. self::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  336. );
  337. }
  338. private function setHandler($prefix, IResponseHandler $handler) {
  339. $this->_prefixHandlers[$prefix] = $handler;
  340. }
  341. public function setOption($option, $value) {
  342. switch ($option) {
  343. case 'iterable_multibulk_replies':
  344. case 'iterableMultiBulkReplies':
  345. $this->setHandler(self::PREFIX_MULTI_BULK, $value == true
  346. ? new ResponseMultiBulkStreamHandler()
  347. : new ResponseMultiBulkHandler()
  348. );
  349. break;
  350. case 'errorThrowException':
  351. case 'error_throw_exception':
  352. $this->setHandler(self::PREFIX_ERROR, $value == true
  353. ? new ResponseErrorHandler()
  354. : new ResponseErrorSilentHandler()
  355. );
  356. break;
  357. default:
  358. throw new \InvalidArgumentException("Unknown option: $option");
  359. }
  360. }
  361. public function getOption($option) {
  362. switch ($option) {
  363. case 'iterable_multibulk_replies':
  364. case 'iterableMultiBulkReplies':
  365. return $this->_prefixHandlers[self::PREFIX_MULTI_BULK]
  366. instanceof ResponseMultiBulkStreamHandler;
  367. case 'errorThrowException':
  368. case 'error_throw_exception':
  369. return $this->_prefixHandlers[self::PREFIX_ERROR]
  370. instanceof ResponseErrorHandler;
  371. default:
  372. throw new \InvalidArgumentException("Unknown option: $option");
  373. }
  374. }
  375. public function read(Connection $connection) {
  376. $header = fgets($connection->getSocket());
  377. if ($header === false) {
  378. throw new ClientException('An error has occurred while reading from the network stream');
  379. }
  380. $prefix = $header[0];
  381. $payload = substr($header, 1, -2);
  382. if (!isset($this->_prefixHandlers[$prefix])) {
  383. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  384. }
  385. $handler = $this->_prefixHandlers[$prefix];
  386. return $handler->handle($connection, $payload);
  387. }
  388. }
  389. class ResponseError {
  390. private $_message;
  391. public function __construct($message) {
  392. $this->_message = $message;
  393. }
  394. public function __get($property) {
  395. if ($property == 'error') {
  396. return true;
  397. }
  398. if ($property == 'message') {
  399. return $this->_message;
  400. }
  401. }
  402. public function __isset($property) {
  403. return $property === 'error';
  404. }
  405. public function __toString() {
  406. return $this->_message;
  407. }
  408. }
  409. class ResponseQueued {
  410. public $queued = true;
  411. public function __toString() {
  412. return ResponseReader::QUEUED;
  413. }
  414. }
  415. /* ------------------------------------------------------------------------- */
  416. class CommandPipeline {
  417. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  418. public function __construct(Client $redisClient) {
  419. $this->_redisClient = $redisClient;
  420. $this->_pipelineBuffer = array();
  421. $this->_returnValues = array();
  422. }
  423. public function __call($method, $arguments) {
  424. $command = $this->_redisClient->createCommand($method, $arguments);
  425. $this->recordCommand($command);
  426. return $this;
  427. }
  428. private function recordCommand(Command $command) {
  429. $this->_pipelineBuffer[] = $command;
  430. }
  431. private function getRecordedCommands() {
  432. return $this->_pipelineBuffer;
  433. }
  434. public function flushPipeline() {
  435. $sizeofPipe = count($this->_pipelineBuffer);
  436. if ($sizeofPipe === 0) {
  437. return;
  438. }
  439. $connection = $this->_redisClient->getConnection();
  440. $commands = &$this->_pipelineBuffer;
  441. foreach ($commands as $command) {
  442. $connection->writeCommand($command);
  443. }
  444. for ($i = 0; $i < $sizeofPipe; $i++) {
  445. $response = $connection->readResponse($commands[$i]);
  446. $this->_returnValues[] = ($response instanceof \Iterator
  447. ? iterator_to_array($response)
  448. : $response
  449. );
  450. unset($commands[$i]);
  451. }
  452. $this->_pipelineBuffer = array();
  453. return $this;
  454. }
  455. private function setRunning($bool) {
  456. if ($bool == true && $this->_running == true) {
  457. throw new ClientException("This pipeline is already opened");
  458. }
  459. $this->_running = $bool;
  460. }
  461. public function execute($block = null) {
  462. if ($block && !is_callable($block)) {
  463. throw new \RuntimeException('Argument passed must be a callable object');
  464. }
  465. // TODO: do not reuse previously executed pipelines
  466. $this->setRunning(true);
  467. $pipelineBlockException = null;
  468. try {
  469. if ($block !== null) {
  470. $block($this);
  471. }
  472. $this->flushPipeline();
  473. }
  474. catch (\Exception $exception) {
  475. // TODO: client/server desync on ServerException
  476. $pipelineBlockException = $exception;
  477. }
  478. $this->setRunning(false);
  479. if ($pipelineBlockException !== null) {
  480. throw $pipelineBlockException;
  481. }
  482. return $this->_returnValues;
  483. }
  484. }
  485. class MultiExecBlock {
  486. private $_redisClient, $_commands, $_initialized, $_discarded;
  487. public function __construct(Client $redisClient) {
  488. $this->_initialized = false;
  489. $this->_discarded = false;
  490. $this->_redisClient = $redisClient;
  491. $this->_commands = array();
  492. }
  493. private function initialize() {
  494. if ($this->_initialized === false) {
  495. $this->_redisClient->multi();
  496. $this->_initialized = true;
  497. $this->_discarded = false;
  498. }
  499. }
  500. public function __call($method, $arguments) {
  501. $this->initialize();
  502. $command = $this->_redisClient->createCommand($method, $arguments);
  503. $response = $this->_redisClient->executeCommand($command);
  504. if (isset($response->queued)) {
  505. $this->_commands[] = $command;
  506. return $this;
  507. }
  508. else {
  509. throw new ClientException('The server did not respond with a QUEUED status reply');
  510. }
  511. }
  512. public function discard() {
  513. $this->_redisClient->discard();
  514. $this->_commands = array();
  515. $this->_initialized = false;
  516. $this->_discarded = true;
  517. }
  518. public function execute($block = null) {
  519. if ($block && !is_callable($block)) {
  520. throw new \RuntimeException('Argument passed must be a callable object');
  521. }
  522. $blockException = null;
  523. $returnValues = array();
  524. try {
  525. if ($block !== null) {
  526. $block($this);
  527. }
  528. if ($this->_discarded === true) {
  529. return;
  530. }
  531. $execReply = (($reply = $this->_redisClient->exec()) instanceof \Iterator
  532. ? iterator_to_array($reply)
  533. : $reply
  534. );
  535. $commands = &$this->_commands;
  536. $sizeofReplies = count($execReply);
  537. if ($sizeofReplies !== count($commands)) {
  538. // TODO: think of a better exception message
  539. throw new ClientException("Out-of-sync");
  540. }
  541. for ($i = 0; $i < $sizeofReplies; $i++) {
  542. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  543. ? iterator_to_array($execReply[$i])
  544. : $execReply[$i]
  545. );
  546. unset($commands[$i]);
  547. }
  548. }
  549. catch (\Exception $exception) {
  550. $blockException = $exception;
  551. }
  552. if ($blockException !== null) {
  553. throw $blockException;
  554. }
  555. return $returnValues;
  556. }
  557. }
  558. /* ------------------------------------------------------------------------- */
  559. class ConnectionParameters {
  560. const DEFAULT_HOST = '127.0.0.1';
  561. const DEFAULT_PORT = 6379;
  562. const DEFAULT_TIMEOUT = 5;
  563. private $_parameters;
  564. public function __construct($parameters = null) {
  565. $parameters = $parameters ?: array();
  566. $this->_parameters = is_array($parameters)
  567. ? self::filterConnectionParams($parameters)
  568. : self::parseURI($parameters);
  569. }
  570. private static function parseURI($uri) {
  571. $parsed = @parse_url($uri);
  572. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  573. throw new ClientException("Invalid URI: $uri");
  574. }
  575. if (array_key_exists('query', $parsed)) {
  576. $details = array();
  577. foreach (explode('&', $parsed['query']) as $kv) {
  578. list($k, $v) = explode('=', $kv);
  579. switch ($k) {
  580. case 'database':
  581. $details['database'] = $v;
  582. break;
  583. case 'password':
  584. $details['password'] = $v;
  585. break;
  586. case 'connection_timeout':
  587. $details['connection_timeout'] = $v;
  588. break;
  589. case 'read_write_timeout':
  590. $details['read_write_timeout'] = $v;
  591. break;
  592. case 'alias':
  593. $details['alias'] = $v;
  594. break;
  595. }
  596. }
  597. $parsed = array_merge($parsed, $details);
  598. }
  599. return self::filterConnectionParams($parsed);
  600. }
  601. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  602. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  603. }
  604. private static function filterConnectionParams($parameters) {
  605. return array(
  606. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  607. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  608. 'database' => self::getParamOrDefault($parameters, 'database'),
  609. 'password' => self::getParamOrDefault($parameters, 'password'),
  610. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  611. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  612. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  613. );
  614. }
  615. public function __get($parameter) {
  616. return $this->_parameters[$parameter];
  617. }
  618. public function __isset($parameter) {
  619. return isset($this->_parameters[$parameter]);
  620. }
  621. }
  622. interface IConnection {
  623. public function connect();
  624. public function disconnect();
  625. public function isConnected();
  626. public function writeCommand(Command $command);
  627. public function readResponse(Command $command);
  628. }
  629. class Connection implements IConnection {
  630. private $_params, $_socket, $_initCmds, $_reader;
  631. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  632. $this->_params = $parameters;
  633. $this->_initCmds = array();
  634. $this->_reader = $reader ?: new ResponseReader();
  635. }
  636. public function __destruct() {
  637. $this->disconnect();
  638. }
  639. public function isConnected() {
  640. return is_resource($this->_socket);
  641. }
  642. public function connect() {
  643. if ($this->isConnected()) {
  644. throw new ClientException('Connection already estabilished');
  645. }
  646. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  647. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $this->_params->connection_timeout);
  648. if (!$this->_socket) {
  649. throw new ClientException(trim($errstr), $errno);
  650. }
  651. if (isset($this->_params->read_write_timeout)) {
  652. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  653. }
  654. if (count($this->_initCmds) > 0){
  655. $this->sendInitializationCommands();
  656. }
  657. }
  658. public function disconnect() {
  659. if ($this->isConnected()) {
  660. fclose($this->_socket);
  661. }
  662. }
  663. public function pushInitCommand(Command $command){
  664. $this->_initCmds[] = $command;
  665. }
  666. private function sendInitializationCommands() {
  667. foreach ($this->_initCmds as $command) {
  668. $this->writeCommand($command);
  669. }
  670. foreach ($this->_initCmds as $command) {
  671. $this->readResponse($command);
  672. }
  673. }
  674. public function writeCommand(Command $command) {
  675. $written = fwrite($this->getSocket(), $command());
  676. if ($written === false){
  677. throw new ClientException(sprintf(
  678. 'An error has occurred while writing command %s on the network stream',
  679. $command->getCommandId()
  680. ));
  681. }
  682. }
  683. public function readResponse(Command $command) {
  684. $response = $this->_reader->read($this);
  685. $skipparse = isset($response->queued) || isset($response->error);
  686. return $skipparse ? $response : $command->parseResponse($response);
  687. }
  688. public function rawCommand($rawCommandData, $closesConnection = false) {
  689. $socket = $this->getSocket();
  690. $written = fwrite($socket, $rawCommandData);
  691. if ($written === false){
  692. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  693. }
  694. if ($closesConnection) {
  695. return;
  696. }
  697. return $this->_reader->read($this);
  698. }
  699. public function getSocket() {
  700. if (!$this->isConnected()) {
  701. $this->connect();
  702. }
  703. return $this->_socket;
  704. }
  705. public function getResponseReader() {
  706. return $this->_reader;
  707. }
  708. public function getAlias() {
  709. return $this->_params->alias;
  710. }
  711. public function __toString() {
  712. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  713. }
  714. }
  715. class ConnectionCluster implements IConnection, \IteratorAggregate {
  716. private $_pool, $_ring;
  717. public function __construct() {
  718. $this->_pool = array();
  719. $this->_ring = new Utilities\HashRing();
  720. }
  721. public function __destruct() {
  722. $this->disconnect();
  723. }
  724. public function isConnected() {
  725. foreach ($this->_pool as $connection) {
  726. if ($connection->isConnected()) {
  727. return true;
  728. }
  729. }
  730. return false;
  731. }
  732. public function connect() {
  733. foreach ($this->_pool as $connection) {
  734. $connection->connect();
  735. }
  736. }
  737. public function disconnect() {
  738. foreach ($this->_pool as $connection) {
  739. $connection->disconnect();
  740. }
  741. }
  742. public function add(Connection $connection) {
  743. $connectionAlias = $connection->getAlias();
  744. if (isset($connectionAlias)) {
  745. $this->_pool[$connectionAlias] = $connection;
  746. }
  747. else {
  748. $this->_pool[] = $connection;
  749. }
  750. $this->_ring->add($connection);
  751. }
  752. private function getConnection(Command $command) {
  753. if ($command->canBeHashed() === false) {
  754. throw new ClientException(
  755. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  756. );
  757. }
  758. return $this->_ring->get($command->getHash());
  759. }
  760. public function getConnectionById($id = null) {
  761. return $this->_pool[$id ?: 0];
  762. }
  763. public function getIterator() {
  764. return new \ArrayIterator($this->_pool);
  765. }
  766. public function writeCommand(Command $command) {
  767. $this->getConnection($command)->writeCommand($command);
  768. }
  769. public function readResponse(Command $command) {
  770. return $this->getConnection($command)->readResponse($command);
  771. }
  772. }
  773. /* ------------------------------------------------------------------------- */
  774. abstract class RedisServerProfile {
  775. private static $_serverProfiles;
  776. private $_registeredCommands;
  777. public function __construct() {
  778. $this->_registeredCommands = $this->getSupportedCommands();
  779. }
  780. public abstract function getVersion();
  781. protected abstract function getSupportedCommands();
  782. public static function getDefault() {
  783. return self::get('default');
  784. }
  785. private static function predisServerProfiles() {
  786. return array(
  787. '1.0' => '\Predis\RedisServer_v1_0',
  788. '1.2' => '\Predis\RedisServer_v1_2',
  789. 'default' => '\Predis\RedisServer_v1_2',
  790. 'dev' => '\Predis\RedisServer_vNext',
  791. );
  792. }
  793. public static function get($version) {
  794. if (!isset(self::$_serverProfiles)) {
  795. self::$_serverProfiles = self::predisServerProfiles();
  796. }
  797. if (!isset(self::$_serverProfiles[$version])) {
  798. throw new ClientException("Unknown server profile: $version");
  799. }
  800. $profile = self::$_serverProfiles[$version];
  801. return new $profile();
  802. }
  803. public function compareWith($version, $operator = null) {
  804. // one could expect that PHP's version_compare would behave
  805. // the same way if invoked with 2 arguments or 3 arguments
  806. // with the third being NULL, but it is not like that.
  807. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  808. // we might need to revise the behavior of this method.
  809. return ($operator === null
  810. ? version_compare($this, $version)
  811. : version_compare($this, $version, $operator)
  812. );
  813. }
  814. public function supportsCommand($command) {
  815. return isset($this->_registeredCommands[$command]);
  816. }
  817. public function createCommand($method, $arguments = array()) {
  818. if (!isset($this->_registeredCommands[$method])) {
  819. throw new ClientException("'$method' is not a registered Redis command");
  820. }
  821. $commandClass = $this->_registeredCommands[$method];
  822. $command = new $commandClass();
  823. $command->setArgumentsArray($arguments);
  824. return $command;
  825. }
  826. public function registerCommands(Array $commands) {
  827. foreach ($commands as $command => $aliases) {
  828. $this->registerCommand($command, $aliases);
  829. }
  830. }
  831. public function registerCommand($command, $aliases) {
  832. $commandReflection = new \ReflectionClass($command);
  833. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  834. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  835. }
  836. if (is_array($aliases)) {
  837. foreach ($aliases as $alias) {
  838. $this->_registeredCommands[$alias] = $command;
  839. }
  840. }
  841. else {
  842. $this->_registeredCommands[$aliases] = $command;
  843. }
  844. }
  845. public function __toString() {
  846. return $this->getVersion();
  847. }
  848. }
  849. class RedisServer_v1_0 extends RedisServerProfile {
  850. public function getVersion() { return '1.0'; }
  851. public function getSupportedCommands() {
  852. return array(
  853. /* miscellaneous commands */
  854. 'ping' => '\Predis\Commands\Ping',
  855. 'echo' => '\Predis\Commands\DoEcho',
  856. 'auth' => '\Predis\Commands\Auth',
  857. /* connection handling */
  858. 'quit' => '\Predis\Commands\Quit',
  859. /* commands operating on string values */
  860. 'set' => '\Predis\Commands\Set',
  861. 'setnx' => '\Predis\Commands\SetPreserve',
  862. 'setPreserve' => '\Predis\Commands\SetPreserve',
  863. 'get' => '\Predis\Commands\Get',
  864. 'mget' => '\Predis\Commands\GetMultiple',
  865. 'getMultiple' => '\Predis\Commands\GetMultiple',
  866. 'getset' => '\Predis\Commands\GetSet',
  867. 'getSet' => '\Predis\Commands\GetSet',
  868. 'incr' => '\Predis\Commands\Increment',
  869. 'increment' => '\Predis\Commands\Increment',
  870. 'incrby' => '\Predis\Commands\IncrementBy',
  871. 'incrementBy' => '\Predis\Commands\IncrementBy',
  872. 'decr' => '\Predis\Commands\Decrement',
  873. 'decrement' => '\Predis\Commands\Decrement',
  874. 'decrby' => '\Predis\Commands\DecrementBy',
  875. 'decrementBy' => '\Predis\Commands\DecrementBy',
  876. 'exists' => '\Predis\Commands\Exists',
  877. 'del' => '\Predis\Commands\Delete',
  878. 'delete' => '\Predis\Commands\Delete',
  879. 'type' => '\Predis\Commands\Type',
  880. /* commands operating on the key space */
  881. 'keys' => '\Predis\Commands\Keys',
  882. 'randomkey' => '\Predis\Commands\RandomKey',
  883. 'randomKey' => '\Predis\Commands\RandomKey',
  884. 'rename' => '\Predis\Commands\Rename',
  885. 'renamenx' => '\Predis\Commands\RenamePreserve',
  886. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  887. 'expire' => '\Predis\Commands\Expire',
  888. 'expireat' => '\Predis\Commands\ExpireAt',
  889. 'expireAt' => '\Predis\Commands\ExpireAt',
  890. 'dbsize' => '\Predis\Commands\DatabaseSize',
  891. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  892. 'ttl' => '\Predis\Commands\TimeToLive',
  893. 'timeToLive' => '\Predis\Commands\TimeToLive',
  894. /* commands operating on lists */
  895. 'rpush' => '\Predis\Commands\ListPushTail',
  896. 'pushTail' => '\Predis\Commands\ListPushTail',
  897. 'lpush' => '\Predis\Commands\ListPushHead',
  898. 'pushHead' => '\Predis\Commands\ListPushHead',
  899. 'llen' => '\Predis\Commands\ListLength',
  900. 'listLength' => '\Predis\Commands\ListLength',
  901. 'lrange' => '\Predis\Commands\ListRange',
  902. 'listRange' => '\Predis\Commands\ListRange',
  903. 'ltrim' => '\Predis\Commands\ListTrim',
  904. 'listTrim' => '\Predis\Commands\ListTrim',
  905. 'lindex' => '\Predis\Commands\ListIndex',
  906. 'listIndex' => '\Predis\Commands\ListIndex',
  907. 'lset' => '\Predis\Commands\ListSet',
  908. 'listSet' => '\Predis\Commands\ListSet',
  909. 'lrem' => '\Predis\Commands\ListRemove',
  910. 'listRemove' => '\Predis\Commands\ListRemove',
  911. 'lpop' => '\Predis\Commands\ListPopFirst',
  912. 'popFirst' => '\Predis\Commands\ListPopFirst',
  913. 'rpop' => '\Predis\Commands\ListPopLast',
  914. 'popLast' => '\Predis\Commands\ListPopLast',
  915. /* commands operating on sets */
  916. 'sadd' => '\Predis\Commands\SetAdd',
  917. 'setAdd' => '\Predis\Commands\SetAdd',
  918. 'srem' => '\Predis\Commands\SetRemove',
  919. 'setRemove' => '\Predis\Commands\SetRemove',
  920. 'spop' => '\Predis\Commands\SetPop',
  921. 'setPop' => '\Predis\Commands\SetPop',
  922. 'smove' => '\Predis\Commands\SetMove',
  923. 'setMove' => '\Predis\Commands\SetMove',
  924. 'scard' => '\Predis\Commands\SetCardinality',
  925. 'setCardinality' => '\Predis\Commands\SetCardinality',
  926. 'sismember' => '\Predis\Commands\SetIsMember',
  927. 'setIsMember' => '\Predis\Commands\SetIsMember',
  928. 'sinter' => '\Predis\Commands\SetIntersection',
  929. 'setIntersection' => '\Predis\Commands\SetIntersection',
  930. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  931. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  932. 'sunion' => '\Predis\Commands\SetUnion',
  933. 'setUnion' => '\Predis\Commands\SetUnion',
  934. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  935. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  936. 'sdiff' => '\Predis\Commands\SetDifference',
  937. 'setDifference' => '\Predis\Commands\SetDifference',
  938. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  939. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  940. 'smembers' => '\Predis\Commands\SetMembers',
  941. 'setMembers' => '\Predis\Commands\SetMembers',
  942. 'srandmember' => '\Predis\Commands\SetRandomMember',
  943. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  944. /* multiple databases handling commands */
  945. 'select' => '\Predis\Commands\SelectDatabase',
  946. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  947. 'move' => '\Predis\Commands\MoveKey',
  948. 'moveKey' => '\Predis\Commands\MoveKey',
  949. 'flushdb' => '\Predis\Commands\FlushDatabase',
  950. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  951. 'flushall' => '\Predis\Commands\FlushAll',
  952. 'flushDatabases' => '\Predis\Commands\FlushAll',
  953. /* sorting */
  954. 'sort' => '\Predis\Commands\Sort',
  955. /* remote server control commands */
  956. 'info' => '\Predis\Commands\Info',
  957. 'slaveof' => '\Predis\Commands\SlaveOf',
  958. 'slaveOf' => '\Predis\Commands\SlaveOf',
  959. /* persistence control commands */
  960. 'save' => '\Predis\Commands\Save',
  961. 'bgsave' => '\Predis\Commands\BackgroundSave',
  962. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  963. 'lastsave' => '\Predis\Commands\LastSave',
  964. 'lastSave' => '\Predis\Commands\LastSave',
  965. 'shutdown' => '\Predis\Commands\Shutdown',
  966. );
  967. }
  968. }
  969. class RedisServer_v1_2 extends RedisServer_v1_0 {
  970. public function getVersion() { return '1.2'; }
  971. public function getSupportedCommands() {
  972. return array_merge(parent::getSupportedCommands(), array(
  973. /* commands operating on string values */
  974. 'mset' => '\Predis\Commands\SetMultiple',
  975. 'setMultiple' => '\Predis\Commands\SetMultiple',
  976. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  977. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  978. /* commands operating on lists */
  979. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  980. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  981. /* commands operating on sorted sets */
  982. 'zadd' => '\Predis\Commands\ZSetAdd',
  983. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  984. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  985. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  986. 'zrem' => '\Predis\Commands\ZSetRemove',
  987. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  988. 'zrange' => '\Predis\Commands\ZSetRange',
  989. 'zsetRange' => '\Predis\Commands\ZSetRange',
  990. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  991. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  992. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  993. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  994. 'zcard' => '\Predis\Commands\ZSetCardinality',
  995. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  996. 'zscore' => '\Predis\Commands\ZSetScore',
  997. 'zsetScore' => '\Predis\Commands\ZSetScore',
  998. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  999. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1000. /* persistence control commands */
  1001. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1002. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1003. ));
  1004. }
  1005. }
  1006. class RedisServer_vNext extends RedisServer_v1_2 {
  1007. public function getVersion() { return '1.3'; }
  1008. public function getSupportedCommands() {
  1009. return array_merge(parent::getSupportedCommands(), array(
  1010. /* miscellaneous commands */
  1011. 'multi' => '\Predis\Commands\Multi',
  1012. 'exec' => '\Predis\Commands\Exec',
  1013. 'discard' => '\Predis\Commands\Discard',
  1014. /* commands operating on string values */
  1015. 'append' => '\Predis\Commands\Append',
  1016. 'substr' => '\Predis\Commands\Substr',
  1017. /* commands operating on lists */
  1018. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1019. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1020. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1021. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1022. /* commands operating on sorted sets */
  1023. 'zunion' => '\Predis\Commands\ZSetUnion',
  1024. 'zsetUnion' => '\Predis\Commands\ZSetUnion',
  1025. 'zinter' => '\Predis\Commands\ZSetIntersection',
  1026. 'zsetIntersection' => '\Predis\Commands\ZSetIntersection',
  1027. 'zcount' => '\Predis\Commands\ZSetCount',
  1028. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1029. 'zrank' => '\Predis\Commands\ZSetRank',
  1030. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1031. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1032. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1033. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1034. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1035. /* commands operating on hashes */
  1036. 'hset' => '\Predis\Commands\HashSet',
  1037. 'hashSet' => '\Predis\Commands\HashSet',
  1038. 'hget' => '\Predis\Commands\HashGet',
  1039. 'hashGet' => '\Predis\Commands\HashGet',
  1040. 'hdel' => '\Predis\Commands\HashDelete',
  1041. 'hashDelete' => '\Predis\Commands\HashDelete',
  1042. 'hlen' => '\Predis\Commands\HashLength',
  1043. 'hashLength' => '\Predis\Commands\HashLength',
  1044. 'hkeys' => '\Predis\Commands\HashKeys',
  1045. 'hashKeys' => '\Predis\Commands\HashKeys',
  1046. 'hvals' => '\Predis\Commands\HashValues',
  1047. 'hashValues' => '\Predis\Commands\HashValues',
  1048. 'hgetall' => '\Predis\Commands\HashGetAll',
  1049. 'hashKeysValues' => '\Predis\Commands\HashGetAll',
  1050. ));
  1051. }
  1052. }
  1053. /* ------------------------------------------------------------------------- */
  1054. namespace Predis\Utilities;
  1055. class HashRing {
  1056. const DEFAULT_REPLICAS = 128;
  1057. private $_ring, $_ringKeys, $_replicas;
  1058. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1059. $this->_replicas = $replicas;
  1060. $this->_ring = array();
  1061. $this->_ringKeys = array();
  1062. }
  1063. public function add($node) {
  1064. $nodeHash = (string) $node;
  1065. $replicas = $this->_replicas;
  1066. for ($i = 0; $i < $replicas; $i++) {
  1067. $key = crc32($nodeHash . ':' . $i);
  1068. $this->_ring[$key] = $node;
  1069. }
  1070. ksort($this->_ring, SORT_NUMERIC);
  1071. $this->_ringKeys = array_keys($this->_ring);
  1072. }
  1073. public function remove($node) {
  1074. $nodeHash = (string) $node;
  1075. $replicas = $this->_replicas;
  1076. for ($i = 0; $i < $replicas; $i++) {
  1077. $key = crc32($nodeHash . ':' . $i);
  1078. unset($this->_ring[$key]);
  1079. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  1080. return $rk !== $key;
  1081. });
  1082. }
  1083. }
  1084. public function get($key) {
  1085. return $this->_ring[$this->getNodeKey($key)];
  1086. }
  1087. private function getNodeKey($key) {
  1088. $ringKeys = $this->_ringKeys;
  1089. $upper = count($ringKeys) - 1;
  1090. $lower = 0;
  1091. $index = 0;
  1092. while ($lower <= $upper) {
  1093. $index = ($lower + $upper) / 2;
  1094. $item = $ringKeys[$index];
  1095. if ($item > $key) {
  1096. $upper = $index - 1;
  1097. }
  1098. else if ($item < $key) {
  1099. $lower = $index + 1;
  1100. }
  1101. else {
  1102. return $index;
  1103. }
  1104. }
  1105. return $ringKeys[$upper];
  1106. }
  1107. }
  1108. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1109. protected $_position, $_current, $_replySize;
  1110. public function rewind() {
  1111. // NOOP
  1112. }
  1113. public function current() {
  1114. return $this->_current;
  1115. }
  1116. public function key() {
  1117. return $this->_position;
  1118. }
  1119. public function next() {
  1120. if (++$this->_position < $this->_replySize) {
  1121. $this->_current = $this->getValue();
  1122. }
  1123. return $this->_position;
  1124. }
  1125. public function valid() {
  1126. return $this->_position < $this->_replySize;
  1127. }
  1128. public function count() {
  1129. // NOTE: use count if you want to get the size of the current multi-bulk
  1130. // response without using iterator_count (which actually consumes
  1131. // our iterator to calculate the size, and we cannot perform a rewind)
  1132. return $this->_replySize;
  1133. }
  1134. protected abstract function getValue();
  1135. }
  1136. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1137. private $_connection;
  1138. public function __construct(\Predis\Connection $connection, $size) {
  1139. $this->_connection = $connection;
  1140. $this->_reader = $connection->getResponseReader();
  1141. $this->_position = 0;
  1142. $this->_current = $size > 0 ? $this->getValue() : null;
  1143. $this->_replySize = $size;
  1144. }
  1145. public function __destruct() {
  1146. // when the iterator is garbage-collected (e.g. it goes out of the
  1147. // scope of a foreach) but it has not reached its end, we must sync
  1148. // the client with the queued elements that have not been read from
  1149. // the connection with the server.
  1150. $this->sync();
  1151. }
  1152. public function sync() {
  1153. while ($this->valid()) {
  1154. $this->next();
  1155. }
  1156. }
  1157. protected function getValue() {
  1158. return $this->_reader->read($this->_connection);
  1159. }
  1160. }
  1161. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1162. private $_iterator;
  1163. public function __construct(MultiBulkResponseIterator $iterator) {
  1164. $virtualSize = count($iterator) / 2;
  1165. $this->_iterator = $iterator;
  1166. $this->_position = 0;
  1167. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1168. $this->_replySize = $virtualSize;
  1169. }
  1170. public function __destruct() {
  1171. $this->_iterator->sync();
  1172. }
  1173. protected function getValue() {
  1174. $k = $this->_iterator->current();
  1175. $this->_iterator->next();
  1176. $v = $this->_iterator->current();
  1177. $this->_iterator->next();
  1178. return array($k, $v);
  1179. }
  1180. }
  1181. /* ------------------------------------------------------------------------- */
  1182. namespace Predis\Commands;
  1183. /* miscellaneous commands */
  1184. class Ping extends \Predis\InlineCommand {
  1185. public function canBeHashed() { return false; }
  1186. public function getCommandId() { return 'PING'; }
  1187. public function parseResponse($data) {
  1188. return $data === 'PONG' ? true : false;
  1189. }
  1190. }
  1191. class DoEcho extends \Predis\BulkCommand {
  1192. public function canBeHashed() { return false; }
  1193. public function getCommandId() { return 'ECHO'; }
  1194. }
  1195. class Auth extends \Predis\InlineCommand {
  1196. public function canBeHashed() { return false; }
  1197. public function getCommandId() { return 'AUTH'; }
  1198. }
  1199. /* connection handling */
  1200. class Quit extends \Predis\InlineCommand {
  1201. public function canBeHashed() { return false; }
  1202. public function getCommandId() { return 'QUIT'; }
  1203. public function closesConnection() { return true; }
  1204. }
  1205. /* commands operating on string values */
  1206. class Set extends \Predis\BulkCommand {
  1207. public function getCommandId() { return 'SET'; }
  1208. }
  1209. class SetPreserve extends \Predis\BulkCommand {
  1210. public function getCommandId() { return 'SETNX'; }
  1211. public function parseResponse($data) { return (bool) $data; }
  1212. }
  1213. class SetMultiple extends \Predis\MultiBulkCommand {
  1214. public function canBeHashed() { return false; }
  1215. public function getCommandId() { return 'MSET'; }
  1216. }
  1217. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1218. public function canBeHashed() { return false; }
  1219. public function getCommandId() { return 'MSETNX'; }
  1220. public function parseResponse($data) { return (bool) $data; }
  1221. }
  1222. class Get extends \Predis\InlineCommand {
  1223. public function getCommandId() { return 'GET'; }
  1224. }
  1225. class GetMultiple extends \Predis\InlineCommand {
  1226. public function canBeHashed() { return false; }
  1227. public function getCommandId() { return 'MGET'; }
  1228. }
  1229. class GetSet extends \Predis\BulkCommand {
  1230. public function getCommandId() { return 'GETSET'; }
  1231. }
  1232. class Increment extends \Predis\InlineCommand {
  1233. public function getCommandId() { return 'INCR'; }
  1234. }
  1235. class IncrementBy extends \Predis\InlineCommand {
  1236. public function getCommandId() { return 'INCRBY'; }
  1237. }
  1238. class Decrement extends \Predis\InlineCommand {
  1239. public function getCommandId() { return 'DECR'; }
  1240. }
  1241. class DecrementBy extends \Predis\InlineCommand {
  1242. public function getCommandId() { return 'DECRBY'; }
  1243. }
  1244. class Exists extends \Predis\InlineCommand {
  1245. public function getCommandId() { return 'EXISTS'; }
  1246. public function parseResponse($data) { return (bool) $data; }
  1247. }
  1248. class Delete extends \Predis\InlineCommand {
  1249. public function getCommandId() { return 'DEL'; }
  1250. public function parseResponse($data) { return (bool) $data; }
  1251. }
  1252. class Type extends \Predis\InlineCommand {
  1253. public function getCommandId() { return 'TYPE'; }
  1254. }
  1255. class Append extends \Predis\BulkCommand {
  1256. public function getCommandId() { return 'APPEND'; }
  1257. }
  1258. class Substr extends \Predis\InlineCommand {
  1259. public function getCommandId() { return 'SUBSTR'; }
  1260. }
  1261. /* commands operating on the key space */
  1262. class Keys extends \Predis\InlineCommand {
  1263. public function canBeHashed() { return false; }
  1264. public function getCommandId() { return 'KEYS'; }
  1265. public function parseResponse($data) {
  1266. // TODO: is this behaviour correct?
  1267. if (is_array($data) || $data instanceof \Iterator) {
  1268. return $data;
  1269. }
  1270. return strlen($data) > 0 ? explode(' ', $data) : array();
  1271. }
  1272. }
  1273. class RandomKey extends \Predis\InlineCommand {
  1274. public function canBeHashed() { return false; }
  1275. public function getCommandId() { return 'RANDOMKEY'; }
  1276. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1277. }
  1278. class Rename extends \Predis\InlineCommand {
  1279. public function canBeHashed() { return false; }
  1280. public function getCommandId() { return 'RENAME'; }
  1281. }
  1282. class RenamePreserve extends \Predis\InlineCommand {
  1283. public function canBeHashed() { return false; }
  1284. public function getCommandId() { return 'RENAMENX'; }
  1285. public function parseResponse($data) { return (bool) $data; }
  1286. }
  1287. class Expire extends \Predis\InlineCommand {
  1288. public function getCommandId() { return 'EXPIRE'; }
  1289. public function parseResponse($data) { return (bool) $data; }
  1290. }
  1291. class ExpireAt extends \Predis\InlineCommand {
  1292. public function getCommandId() { return 'EXPIREAT'; }
  1293. public function parseResponse($data) { return (bool) $data; }
  1294. }
  1295. class DatabaseSize extends \Predis\InlineCommand {
  1296. public function canBeHashed() { return false; }
  1297. public function getCommandId() { return 'DBSIZE'; }
  1298. }
  1299. class TimeToLive extends \Predis\InlineCommand {
  1300. public function getCommandId() { return 'TTL'; }
  1301. }
  1302. /* commands operating on lists */
  1303. class ListPushTail extends \Predis\BulkCommand {
  1304. public function getCommandId() { return 'RPUSH'; }
  1305. }
  1306. class ListPushHead extends \Predis\BulkCommand {
  1307. public function getCommandId() { return 'LPUSH'; }
  1308. }
  1309. class ListLength extends \Predis\InlineCommand {
  1310. public function getCommandId() { return 'LLEN'; }
  1311. }
  1312. class ListRange extends \Predis\InlineCommand {
  1313. public function getCommandId() { return 'LRANGE'; }
  1314. }
  1315. class ListTrim extends \Predis\InlineCommand {
  1316. public function getCommandId() { return 'LTRIM'; }
  1317. }
  1318. class ListIndex extends \Predis\InlineCommand {
  1319. public function getCommandId() { return 'LINDEX'; }
  1320. }
  1321. class ListSet extends \Predis\BulkCommand {
  1322. public function getCommandId() { return 'LSET'; }
  1323. }
  1324. class ListRemove extends \Predis\BulkCommand {
  1325. public function getCommandId() { return 'LREM'; }
  1326. }
  1327. class ListPopLastPushHead extends \Predis\InlineCommand {
  1328. public function getCommandId() { return 'RPOPLPUSH'; }
  1329. }
  1330. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1331. public function getCommandId() { return 'RPOPLPUSH'; }
  1332. }
  1333. class ListPopFirst extends \Predis\InlineCommand {
  1334. public function getCommandId() { return 'LPOP'; }
  1335. }
  1336. class ListPopLast extends \Predis\InlineCommand {
  1337. public function getCommandId() { return 'RPOP'; }
  1338. }
  1339. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1340. public function getCommandId() { return 'BLPOP'; }
  1341. }
  1342. class ListPopLastBlocking extends \Predis\InlineCommand {
  1343. public function getCommandId() { return 'BRPOP'; }
  1344. }
  1345. /* commands operating on sets */
  1346. class SetAdd extends \Predis\BulkCommand {
  1347. public function getCommandId() { return 'SADD'; }
  1348. public function parseResponse($data) { return (bool) $data; }
  1349. }
  1350. class SetRemove extends \Predis\BulkCommand {
  1351. public function getCommandId() { return 'SREM'; }
  1352. public function parseResponse($data) { return (bool) $data; }
  1353. }
  1354. class SetPop extends \Predis\InlineCommand {
  1355. public function getCommandId() { return 'SPOP'; }
  1356. }
  1357. class SetMove extends \Predis\BulkCommand {
  1358. public function canBeHashed() { return false; }
  1359. public function getCommandId() { return 'SMOVE'; }
  1360. public function parseResponse($data) { return (bool) $data; }
  1361. }
  1362. class SetCardinality extends \Predis\InlineCommand {
  1363. public function getCommandId() { return 'SCARD'; }
  1364. }
  1365. class SetIsMember extends \Predis\BulkCommand {
  1366. public function getCommandId() { return 'SISMEMBER'; }
  1367. public function parseResponse($data) { return (bool) $data; }
  1368. }
  1369. class SetIntersection extends \Predis\InlineCommand {
  1370. public function getCommandId() { return 'SINTER'; }
  1371. }
  1372. class SetIntersectionStore extends \Predis\InlineCommand {
  1373. public function getCommandId() { return 'SINTERSTORE'; }
  1374. }
  1375. class SetUnion extends \Predis\InlineCommand {
  1376. public function getCommandId() { return 'SUNION'; }
  1377. }
  1378. class SetUnionStore extends \Predis\InlineCommand {
  1379. public function getCommandId() { return 'SUNIONSTORE'; }
  1380. }
  1381. class SetDifference extends \Predis\InlineCommand {
  1382. public function getCommandId() { return 'SDIFF'; }
  1383. }
  1384. class SetDifferenceStore extends \Predis\InlineCommand {
  1385. public function getCommandId() { return 'SDIFFSTORE'; }
  1386. }
  1387. class SetMembers extends \Predis\InlineCommand {
  1388. public function getCommandId() { return 'SMEMBERS'; }
  1389. }
  1390. class SetRandomMember extends \Predis\InlineCommand {
  1391. public function getCommandId() { return 'SRANDMEMBER'; }
  1392. }
  1393. /* commands operating on sorted sets */
  1394. class ZSetAdd extends \Predis\BulkCommand {
  1395. public function getCommandId() { return 'ZADD'; }
  1396. public function parseResponse($data) { return (bool) $data; }
  1397. }
  1398. class ZSetIncrementBy extends \Predis\BulkCommand {
  1399. public function getCommandId() { return 'ZINCRBY'; }
  1400. }
  1401. class ZSetRemove extends \Predis\BulkCommand {
  1402. public function getCommandId() { return 'ZREM'; }
  1403. public function parseResponse($data) { return (bool) $data; }
  1404. }
  1405. class ZSetUnion extends \Predis\InlineCommand {
  1406. public function getCommandId() { return 'ZUNION'; }
  1407. }
  1408. class ZSetIntersection extends \Predis\InlineCommand {
  1409. public function getCommandId() { return 'ZINTER'; }
  1410. }
  1411. class ZSetRange extends \Predis\InlineCommand {
  1412. public function getCommandId() { return 'ZRANGE'; }
  1413. public function parseResponse($data) {
  1414. $arguments = $this->getArguments();
  1415. if (count($arguments) === 4) {
  1416. if (strtolower($arguments[3]) === 'withscores') {
  1417. if ($data instanceof \Iterator) {
  1418. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1419. }
  1420. $result = array();
  1421. for ($i = 0; $i < count($data); $i++) {
  1422. $result[] = array($data[$i], $data[++$i]);
  1423. }
  1424. return $result;
  1425. }
  1426. }
  1427. return $data;
  1428. }
  1429. }
  1430. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1431. public function getCommandId() { return 'ZREVRANGE'; }
  1432. }
  1433. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1434. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1435. }
  1436. class ZSetCount extends \Predis\InlineCommand {
  1437. public function getCommandId() { return 'ZCOUNT'; }
  1438. }
  1439. class ZSetCardinality extends \Predis\InlineCommand {
  1440. public function getCommandId() { return 'ZCARD'; }
  1441. }
  1442. class ZSetScore extends \Predis\BulkCommand {
  1443. public function getCommandId() { return 'ZSCORE'; }
  1444. }
  1445. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1446. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1447. }
  1448. class ZSetRank extends \Predis\BulkCommand {
  1449. public function getCommandId() { return 'ZRANK'; }
  1450. }
  1451. class ZSetReverseRank extends \Predis\BulkCommand {
  1452. public function getCommandId() { return 'ZREVRANK'; }
  1453. }
  1454. class ZSetRemoveRangeByRank extends \Predis\InlineCommand {
  1455. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1456. }
  1457. /* commands operating on hashes */
  1458. class HashSet extends \Predis\MultiBulkCommand {
  1459. public function getCommandId() { return 'HSET'; }
  1460. }
  1461. class HashGet extends \Predis\BulkCommand {
  1462. public function getCommandId() { return 'HGET'; }
  1463. }
  1464. class HashDelete extends \Predis\BulkCommand {
  1465. public function getCommandId() { return 'HDEL'; }
  1466. }
  1467. class HashLength extends \Predis\InlineCommand {
  1468. public function getCommandId() { return 'HLEN'; }
  1469. }
  1470. class HashKeys extends \Predis\InlineCommand {
  1471. public function getCommandId() { return 'HKEYS'; }
  1472. }
  1473. class HashValues extends \Predis\InlineCommand {
  1474. public function getCommandId() { return 'HVALS'; }
  1475. }
  1476. class HashGetAll extends \Predis\InlineCommand {
  1477. public function getCommandId() { return 'HGETALL'; }
  1478. }
  1479. /* multiple databases handling commands */
  1480. class SelectDatabase extends \Predis\InlineCommand {
  1481. public function canBeHashed() { return false; }
  1482. public function getCommandId() { return 'SELECT'; }
  1483. }
  1484. class MoveKey extends \Predis\InlineCommand {
  1485. public function canBeHashed() { return false; }
  1486. public function getCommandId() { return 'MOVE'; }
  1487. public function parseResponse($data) { return (bool) $data; }
  1488. }
  1489. class FlushDatabase extends \Predis\InlineCommand {
  1490. public function canBeHashed() { return false; }
  1491. public function getCommandId() { return 'FLUSHDB'; }
  1492. }
  1493. class FlushAll extends \Predis\InlineCommand {
  1494. public function canBeHashed() { return false; }
  1495. public function getCommandId() { return 'FLUSHALL'; }
  1496. }
  1497. /* sorting */
  1498. class Sort extends \Predis\InlineCommand {
  1499. public function getCommandId() { return 'SORT'; }
  1500. public function filterArguments(Array $arguments) {
  1501. if (count($arguments) === 1) {
  1502. return $arguments;
  1503. }
  1504. // TODO: add more parameters checks
  1505. $query = array($arguments[0]);
  1506. $sortParams = $arguments[1];
  1507. if (isset($sortParams['by'])) {
  1508. $query[] = 'BY ' . $sortParams['by'];
  1509. }
  1510. if (isset($sortParams['get'])) {
  1511. $getargs = $sortParams['get'];
  1512. if (is_array($getargs)) {
  1513. foreach ($getargs as $getarg) {
  1514. $query[] = 'GET ' . $getarg;
  1515. }
  1516. }
  1517. else {
  1518. $query[] = 'GET ' . $getargs;
  1519. }
  1520. }
  1521. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1522. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1523. }
  1524. if (isset($sortParams['sort'])) {
  1525. $query[] = strtoupper($sortParams['sort']);
  1526. }
  1527. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1528. $query[] = 'ALPHA';
  1529. }
  1530. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1531. $query[] = 'STORE ' . $sortParams['store'];
  1532. }
  1533. return $query;
  1534. }
  1535. }
  1536. /* persistence control commands */
  1537. class Save extends \Predis\InlineCommand {
  1538. public function canBeHashed() { return false; }
  1539. public function getCommandId() { return 'SAVE'; }
  1540. }
  1541. class BackgroundSave extends \Predis\InlineCommand {
  1542. public function canBeHashed() { return false; }
  1543. public function getCommandId() { return 'BGSAVE'; }
  1544. public function parseResponse($data) {
  1545. if ($data == 'Background saving started') {
  1546. return true;
  1547. }
  1548. return $data;
  1549. }
  1550. }
  1551. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1552. public function canBeHashed() { return false; }
  1553. public function getCommandId() { return 'BGREWRITEAOF'; }
  1554. public function parseResponse($data) {
  1555. return $data == 'Background append only file rewriting started';
  1556. }
  1557. }
  1558. class LastSave extends \Predis\InlineCommand {
  1559. public function canBeHashed() { return false; }
  1560. public function getCommandId() { return 'LASTSAVE'; }
  1561. }
  1562. class Shutdown extends \Predis\InlineCommand {
  1563. public function canBeHashed() { return false; }
  1564. public function getCommandId() { return 'SHUTDOWN'; }
  1565. public function closesConnection() { return true; }
  1566. }
  1567. /* remote server control commands */
  1568. class Info extends \Predis\InlineCommand {
  1569. public function canBeHashed() { return false; }
  1570. public function getCommandId() { return 'INFO'; }
  1571. public function parseResponse($data) {
  1572. $info = array();
  1573. $infoLines = explode("\r\n", $data, -1);
  1574. foreach ($infoLines as $row) {
  1575. list($k, $v) = explode(':', $row);
  1576. if (!preg_match('/^db\d+$/', $k)) {
  1577. $info[$k] = $v;
  1578. }
  1579. else {
  1580. $db = array();
  1581. foreach (explode(',', $v) as $dbvar) {
  1582. list($dbvk, $dbvv) = explode('=', $dbvar);
  1583. $db[trim($dbvk)] = $dbvv;
  1584. }
  1585. $info[$k] = $db;
  1586. }
  1587. }
  1588. return $info;
  1589. }
  1590. }
  1591. class SlaveOf extends \Predis\InlineCommand {
  1592. public function canBeHashed() { return false; }
  1593. public function getCommandId() { return 'SLAVEOF'; }
  1594. public function filterArguments(Array $arguments) {
  1595. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1596. }
  1597. }
  1598. class Multi extends \Predis\InlineCommand {
  1599. public function canBeHashed() { return false; }
  1600. public function getCommandId() { return 'MULTI'; }
  1601. }
  1602. class Exec extends \Predis\InlineCommand {
  1603. public function canBeHashed() { return false; }
  1604. public function getCommandId() { return 'EXEC'; }
  1605. }
  1606. class Discard extends \Predis\InlineCommand {
  1607. public function canBeHashed() { return false; }
  1608. public function getCommandId() { return 'DISCARD'; }
  1609. }
  1610. ?>