Predis.php 66 KB

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