Predis.php 66 KB

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