Predis.php 63 KB

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