Predis.php 63 KB

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