Predis.php 63 KB

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