Predis.php 63 KB

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