Predis.php 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443
  1. <?php
  2. class PredisException extends Exception { }
  3. // Client-side errors
  4. class Predis_ClientException extends PredisException { }
  5. // Server-side errors
  6. class Predis_ServerException extends PredisException {
  7. public function toResponseError() {
  8. return new ResponseError($this->getMessage());
  9. }
  10. }
  11. // Communication errors
  12. class Predis_CommunicationException extends PredisException {
  13. private $_connection;
  14. public function __construct(Predis_Connection $connection, $message = null, $code = null) {
  15. $this->_connection = $connection;
  16. parent::__construct($message, $code);
  17. }
  18. public function getConnection() { return $this->_connection; }
  19. public function shouldResetConnection() { return true; }
  20. }
  21. // Unexpected responses
  22. class Predis_MalformedServerResponse extends Predis_CommunicationException { }
  23. /* ------------------------------------------------------------------------- */
  24. class Predis_Client {
  25. private $_options, $_connection, $_serverProfile, $_responseReader;
  26. public function __construct($parameters = null, $clientOptions = null) {
  27. $this->setupClient($clientOptions !== null ? $clientOptions : new Predis_ClientOptions());
  28. $this->setupConnection($parameters);
  29. }
  30. public static function create(/* arguments */) {
  31. $argv = func_get_args();
  32. $argc = func_num_args();
  33. $options = null;
  34. $lastArg = $argv[$argc-1];
  35. if ($argc > 0 && !is_string($lastArg) && ($lastArg instanceof Predis_ClientOptions ||
  36. is_subclass_of($lastArg, 'Predis_RedisServerProfile'))) {
  37. $options = array_pop($argv);
  38. $argc--;
  39. }
  40. if ($argc === 0) {
  41. throw new Predis_ClientException('Missing connection parameters');
  42. }
  43. return new Predis_Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  44. }
  45. private static function filterClientOptions($options) {
  46. if ($options instanceof Predis_ClientOptions) {
  47. return $options;
  48. }
  49. if (is_array($options)) {
  50. return new Predis_ClientOptions($options);
  51. }
  52. if ($options instanceof Predis_RedisServerProfile) {
  53. return new Predis_ClientOptions(array(
  54. 'profile' => $options
  55. ));
  56. }
  57. if (is_string($options)) {
  58. return new Predis_ClientOptions(array(
  59. 'profile' => Predis_RedisServerProfile::get($options)
  60. ));
  61. }
  62. throw new InvalidArgumentException("Invalid type for client options");
  63. }
  64. private function setupClient($options) {
  65. $this->_responseReader = new Predis_ResponseReader();
  66. $this->_options = self::filterClientOptions($options);
  67. $this->setProfile($this->_options->profile);
  68. if ($this->_options->iterable_multibulk === true) {
  69. $this->_responseReader->setHandler(
  70. Predis_Protocol::PREFIX_MULTI_BULK,
  71. new Predis_ResponseMultiBulkStreamHandler()
  72. );
  73. }
  74. if ($this->_options->throw_on_error === false) {
  75. $this->_responseReader->setHandler(
  76. Predis_Protocol::PREFIX_ERROR,
  77. new Predis_ResponseErrorSilentHandler()
  78. );
  79. }
  80. }
  81. private function setupConnection($parameters) {
  82. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  83. throw new Predis_ClientException('Invalid parameters type (array or string expected)');
  84. }
  85. if (is_array($parameters) && isset($parameters[0])) {
  86. $cluster = new Predis_ConnectionCluster($this->_options->key_distribution);
  87. foreach ($parameters as $shardParams) {
  88. $cluster->add($this->createConnection($shardParams));
  89. }
  90. $this->setConnection($cluster);
  91. }
  92. else {
  93. $this->setConnection($this->createConnection($parameters));
  94. }
  95. }
  96. private function createConnection($parameters) {
  97. $params = new Predis_ConnectionParameters($parameters);
  98. $connection = new Predis_Connection($params, $this->_responseReader);
  99. if ($params->password !== null) {
  100. $connection->pushInitCommand($this->createCommand(
  101. 'auth', array($params->password)
  102. ));
  103. }
  104. if ($params->database !== null) {
  105. $connection->pushInitCommand($this->createCommand(
  106. 'select', array($params->database)
  107. ));
  108. }
  109. return $connection;
  110. }
  111. private function setConnection(Predis_IConnection $connection) {
  112. $this->_connection = $connection;
  113. }
  114. public function setProfile($serverProfile) {
  115. if (!($serverProfile instanceof Predis_RedisServerProfile || is_string($serverProfile))) {
  116. throw new InvalidArgumentException(
  117. "Invalid type for server profile, Predis_RedisServerProfile or string expected"
  118. );
  119. }
  120. $this->_serverProfile = (is_string($serverProfile)
  121. ? Predis_RedisServerProfile::get($serverProfile)
  122. : $serverProfile
  123. );
  124. }
  125. public function getProfile() {
  126. return $this->_serverProfile;
  127. }
  128. public function getResponseReader() {
  129. return $this->_responseReader;
  130. }
  131. public function connect() {
  132. $this->_connection->connect();
  133. }
  134. public function disconnect() {
  135. $this->_connection->disconnect();
  136. }
  137. public function isConnected() {
  138. return $this->_connection->isConnected();
  139. }
  140. public function getConnection($id = null) {
  141. if (!isset($id)) {
  142. return $this->_connection;
  143. }
  144. else {
  145. return $this->_connection instanceof Predis_ConnectionCluster
  146. ? $this->_connection->getConnectionById($id)
  147. : $this->_connection;
  148. }
  149. }
  150. public function __call($method, $arguments) {
  151. $command = $this->_serverProfile->createCommand($method, $arguments);
  152. return $this->_connection->executeCommand($command);
  153. }
  154. public function createCommand($method, $arguments = array()) {
  155. return $this->_serverProfile->createCommand($method, $arguments);
  156. }
  157. public function executeCommand(Command $command) {
  158. return $this->_connection->executeCommand($command);
  159. }
  160. public function executeCommandOnShards(Command $command) {
  161. $replies = array();
  162. if ($this->_connection instanceof Predis_ConnectionCluster) {
  163. foreach($this->_connection as $connection) {
  164. $replies[] = $connection->executeCommand($command);
  165. }
  166. }
  167. else {
  168. $replies[] = $this->_connection->executeCommand($command);
  169. }
  170. return $replies;
  171. }
  172. public function rawCommand($rawCommandData, $closesConnection = false) {
  173. if ($this->_connection instanceof Predis_ConnectionCluster) {
  174. throw new Predis_ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  175. }
  176. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  177. }
  178. public function pipeline($pipelineBlock = null) {
  179. $pipeline = new Predis_CommandPipeline($this);
  180. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  181. }
  182. public function multiExec($multiExecBlock = null) {
  183. $multiExec = new Predis_MultiExecBlock($this);
  184. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  185. }
  186. }
  187. /* ------------------------------------------------------------------------- */
  188. interface Predis_IClientOptionsHandler {
  189. public function validate($option, $value);
  190. public function getDefault();
  191. }
  192. class Predis_ClientOptionsProfile implements Predis_IClientOptionsHandler {
  193. public function validate($option, $value) {
  194. if ($value instanceof Predis_RedisServerProfile) {
  195. return $value;
  196. }
  197. if (is_string($value)) {
  198. return Predis_RedisServerProfile::get($value);
  199. }
  200. throw new InvalidArgumentException("Invalid value for option $option");
  201. }
  202. public function getDefault() {
  203. return Predis_RedisServerProfile::getDefault();
  204. }
  205. }
  206. class Predis_ClientOptionsKeyDistribution implements Predis_IClientOptionsHandler {
  207. public function validate($option, $value) {
  208. if ($value instanceof Predis_IDistributionAlgorithm) {
  209. return $value;
  210. }
  211. if (is_string($value)) {
  212. $valueReflection = new ReflectionClass($value);
  213. if ($valueReflection->isSubclassOf('Predis_IDistributionAlgorithm')) {
  214. return new $value;
  215. }
  216. }
  217. throw new InvalidArgumentException("Invalid value for option $option");
  218. }
  219. public function getDefault() {
  220. return new Predis_Utilities_HashRing();
  221. }
  222. }
  223. class Predis_ClientOptionsIterableMultiBulk implements Predis_IClientOptionsHandler {
  224. public function validate($option, $value) {
  225. return (bool) $value;
  226. }
  227. public function getDefault() {
  228. return false;
  229. }
  230. }
  231. class Predis_ClientOptionsThrowOnError implements Predis_IClientOptionsHandler {
  232. public function validate($option, $value) {
  233. return (bool) $value;
  234. }
  235. public function getDefault() {
  236. return true;
  237. }
  238. }
  239. class Predis_ClientOptions {
  240. private static $_optionsHandlers;
  241. private $_options;
  242. public function __construct($options = null) {
  243. self::initializeOptionsHandlers();
  244. $this->initializeOptions($options !== null ? $options : array());
  245. }
  246. private static function initializeOptionsHandlers() {
  247. if (!isset(self::$_optionsHandlers)) {
  248. self::$_optionsHandlers = self::getOptionsHandlers();
  249. }
  250. }
  251. private static function getOptionsHandlers() {
  252. return array(
  253. 'profile' => new Predis_ClientOptionsProfile(),
  254. 'key_distribution' => new Predis_ClientOptionsKeyDistribution(),
  255. 'iterable_multibulk' => new Predis_ClientOptionsIterableMultiBulk(),
  256. 'throw_on_error' => new Predis_ClientOptionsThrowOnError(),
  257. );
  258. }
  259. private function initializeOptions($options) {
  260. foreach ($options as $option => $value) {
  261. if (isset(self::$_optionsHandlers[$option])) {
  262. $handler = self::$_optionsHandlers[$option];
  263. $this->_options[$option] = $handler->validate($option, $value);
  264. }
  265. }
  266. }
  267. public function __get($option) {
  268. if (!isset($this->_options[$option])) {
  269. $defaultValue = self::$_optionsHandlers[$option]->getDefault();
  270. $this->_options[$option] = $defaultValue;
  271. }
  272. return $this->_options[$option];
  273. }
  274. public function __isset($option) {
  275. return isset(self::$_optionsHandlers[$option]);
  276. }
  277. }
  278. /* ------------------------------------------------------------------------- */
  279. class Predis_Protocol {
  280. const NEWLINE = "\r\n";
  281. const OK = 'OK';
  282. const ERROR = 'ERR';
  283. const QUEUED = 'QUEUED';
  284. const NULL = 'nil';
  285. const PREFIX_STATUS = '+';
  286. const PREFIX_ERROR = '-';
  287. const PREFIX_INTEGER = ':';
  288. const PREFIX_BULK = '$';
  289. const PREFIX_MULTI_BULK = '*';
  290. }
  291. abstract class Predis_Command {
  292. private $_arguments, $_hash;
  293. public abstract function getCommandId();
  294. public abstract function serializeRequest($command, $arguments);
  295. public function canBeHashed() {
  296. return true;
  297. }
  298. public function getHash(Predis_IDistributionAlgorithm $distributor) {
  299. if (isset($this->_hash)) {
  300. return $this->_hash;
  301. }
  302. else {
  303. if (isset($this->_arguments[0])) {
  304. $key = $this->_arguments[0];
  305. $start = strpos($key, '{');
  306. $end = strpos($key, '}');
  307. if ($start !== false && $end !== false) {
  308. $key = substr($key, ++$start, $end - $start);
  309. }
  310. $this->_hash = $distributor->generateKey($key);
  311. return $this->_hash;
  312. }
  313. }
  314. return null;
  315. }
  316. public function closesConnection() {
  317. return false;
  318. }
  319. protected function filterArguments(Array $arguments) {
  320. return $arguments;
  321. }
  322. public function setArguments(/* arguments */) {
  323. $this->_arguments = $this->filterArguments(func_get_args());
  324. $this->_hash = null;
  325. }
  326. public function setArgumentsArray(Array $arguments) {
  327. $this->_arguments = $this->filterArguments($arguments);
  328. $this->_hash = null;
  329. }
  330. protected function getArguments() {
  331. // TODO: why getArguments is protected?
  332. return isset($this->_arguments) ? $this->_arguments : array();
  333. }
  334. public function getArgument($index = 0) {
  335. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  336. }
  337. public function parseResponse($data) {
  338. return $data;
  339. }
  340. public final function invoke() {
  341. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  342. }
  343. }
  344. abstract class Predis_InlineCommand extends Predis_Command {
  345. public function serializeRequest($command, $arguments) {
  346. if (isset($arguments[0]) && is_array($arguments[0])) {
  347. $arguments[0] = implode($arguments[0], ' ');
  348. }
  349. return $command . ' ' . implode($arguments, ' ') . Predis_Protocol::NEWLINE;
  350. }
  351. }
  352. abstract class Predis_BulkCommand extends Predis_Command {
  353. public function serializeRequest($command, $arguments) {
  354. $data = array_pop($arguments);
  355. if (is_array($data)) {
  356. $data = implode($data, ' ');
  357. }
  358. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  359. Predis_Protocol::NEWLINE . $data . Predis_Protocol::NEWLINE;
  360. }
  361. }
  362. abstract class Predis_MultiBulkCommand extends Predis_Command {
  363. public function serializeRequest($command, $arguments) {
  364. $cmd_args = null;
  365. $argsc = count($arguments);
  366. if ($argsc === 1 && is_array($arguments[0])) {
  367. $cmd_args = $arguments[0];
  368. $argsc = count($cmd_args);
  369. }
  370. else {
  371. $cmd_args = $arguments;
  372. }
  373. $newline = Predis_Protocol::NEWLINE;
  374. $cmdlen = strlen($command);
  375. $reqlen = $argsc + 1;
  376. $buffer = "*{$reqlen}{$newline}\${$cmdlen}{$newline}{$command}{$newline}";
  377. foreach ($cmd_args as $argument) {
  378. $arglen = strlen($argument);
  379. $buffer .= "\${$arglen}{$newline}{$argument}{$newline}";
  380. }
  381. return $buffer;
  382. }
  383. }
  384. /* ------------------------------------------------------------------------- */
  385. interface Predis_IResponseHandler {
  386. function handle(Predis_Connection $connection, $payload);
  387. }
  388. class Predis_ResponseStatusHandler implements Predis_IResponseHandler {
  389. public function handle(Predis_Connection $connection, $status) {
  390. if ($status === Predis_Protocol::OK) {
  391. return true;
  392. }
  393. else if ($status === Predis_Protocol::QUEUED) {
  394. return new Predis_ResponseQueued();
  395. }
  396. return $status;
  397. }
  398. }
  399. class Predis_ResponseErrorHandler implements Predis_IResponseHandler {
  400. public function handle(Predis_Connection $connection, $errorMessage) {
  401. throw new Predis_ServerException(substr($errorMessage, 4));
  402. }
  403. }
  404. class Predis_ResponseErrorSilentHandler implements Predis_IResponseHandler {
  405. public function handle(Predis_Connection $connection, $errorMessage) {
  406. return new Predis_ResponseError(substr($errorMessage, 4));
  407. }
  408. }
  409. class Predis_ResponseBulkHandler implements Predis_IResponseHandler {
  410. public function handle(Predis_Connection $connection, $dataLength) {
  411. if (!is_numeric($dataLength)) {
  412. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  413. $connection, "Cannot parse '$dataLength' as data length"
  414. ));
  415. }
  416. if ($dataLength > 0) {
  417. $value = $connection->readBytes($dataLength);
  418. self::discardNewLine($connection);
  419. return $value;
  420. }
  421. else if ($dataLength == 0) {
  422. self::discardNewLine($connection);
  423. return '';
  424. }
  425. return null;
  426. }
  427. private static function discardNewLine(Predis_Connection $connection) {
  428. if ($connection->readBytes(2) !== Predis_Protocol::NEWLINE) {
  429. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  430. $connection, 'Did not receive a new-line at the end of a bulk response'
  431. ));
  432. }
  433. }
  434. }
  435. class Predis_ResponseMultiBulkHandler implements Predis_IResponseHandler {
  436. public function handle(Predis_Connection $connection, $rawLength) {
  437. if (!is_numeric($rawLength)) {
  438. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  439. $connection, "Cannot parse '$rawLength' as data length"
  440. ));
  441. }
  442. $listLength = (int) $rawLength;
  443. if ($listLength === -1) {
  444. return null;
  445. }
  446. $list = array();
  447. if ($listLength > 0) {
  448. for ($i = 0; $i < $listLength; $i++) {
  449. $list[] = $connection->getResponseReader()->read($connection);
  450. }
  451. }
  452. return $list;
  453. }
  454. }
  455. class Predis_ResponseMultiBulkStreamHandler implements Predis_IResponseHandler {
  456. public function handle(Predis_Connection $connection, $rawLength) {
  457. if (!is_numeric($rawLength)) {
  458. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  459. $connection, "Cannot parse '$rawLength' as data length"
  460. ));
  461. }
  462. return new Predis_Utilities_MultiBulkResponseIterator($connection, (int)$rawLength);
  463. }
  464. }
  465. class Predis_ResponseIntegerHandler implements Predis_IResponseHandler {
  466. public function handle(Predis_Connection $connection, $number) {
  467. if (is_numeric($number)) {
  468. return (int) $number;
  469. }
  470. else {
  471. if ($number !== Predis_Protocol::NULL) {
  472. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  473. $connection, "Cannot parse '$number' as numeric response"
  474. ));
  475. }
  476. return null;
  477. }
  478. }
  479. }
  480. class Predis_ResponseReader {
  481. private $_prefixHandlers;
  482. public function __construct() {
  483. $this->initializePrefixHandlers();
  484. }
  485. private function initializePrefixHandlers() {
  486. $this->_prefixHandlers = array(
  487. Predis_Protocol::PREFIX_STATUS => new Predis_ResponseStatusHandler(),
  488. Predis_Protocol::PREFIX_ERROR => new Predis_ResponseErrorHandler(),
  489. Predis_Protocol::PREFIX_INTEGER => new Predis_ResponseIntegerHandler(),
  490. Predis_Protocol::PREFIX_BULK => new Predis_ResponseBulkHandler(),
  491. Predis_Protocol::PREFIX_MULTI_BULK => new Predis_ResponseMultiBulkHandler(),
  492. );
  493. }
  494. public function setHandler($prefix, Predis_IResponseHandler $handler) {
  495. $this->_prefixHandlers[$prefix] = $handler;
  496. }
  497. public function getHandler($prefix) {
  498. if (isset($this->_prefixHandlers[$prefix])) {
  499. return $this->_prefixHandlers[$prefix];
  500. }
  501. }
  502. public function read(Predis_Connection $connection) {
  503. $header = $connection->readLine();
  504. if ($header === '') {
  505. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  506. $connection, 'Unexpected empty header'
  507. ));
  508. }
  509. $prefix = $header[0];
  510. $payload = strlen($header) > 1 ? substr($header, 1) : '';
  511. if (!isset($this->_prefixHandlers[$prefix])) {
  512. Predis_Utilities_Shared::onCommunicationException(new Predis_MalformedServerResponse(
  513. $connection, "Unknown prefix '$prefix'"
  514. ));
  515. }
  516. $handler = $this->_prefixHandlers[$prefix];
  517. return $handler->handle($connection, $payload);
  518. }
  519. }
  520. class Predis_ResponseError {
  521. private $_message;
  522. public function __construct($message) {
  523. $this->_message = $message;
  524. }
  525. public function __get($property) {
  526. if ($property == 'error') {
  527. return true;
  528. }
  529. if ($property == 'message') {
  530. return $this->_message;
  531. }
  532. }
  533. public function __isset($property) {
  534. return $property === 'error';
  535. }
  536. public function __toString() {
  537. return $this->_message;
  538. }
  539. }
  540. class Predis_ResponseQueued {
  541. public $queued = true;
  542. public function __toString() {
  543. return Predis_Protocol::QUEUED;
  544. }
  545. }
  546. /* ------------------------------------------------------------------------- */
  547. class Predis_CommandPipeline {
  548. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  549. public function __construct(Predis_Client $redisClient) {
  550. $this->_redisClient = $redisClient;
  551. $this->_pipelineBuffer = array();
  552. $this->_returnValues = array();
  553. }
  554. public function __call($method, $arguments) {
  555. $command = $this->_redisClient->createCommand($method, $arguments);
  556. $this->recordCommand($command);
  557. return $this;
  558. }
  559. private function recordCommand(Predis_Command $command) {
  560. $this->_pipelineBuffer[] = $command;
  561. }
  562. private function getRecordedCommands() {
  563. return $this->_pipelineBuffer;
  564. }
  565. public function flushPipeline() {
  566. $sizeofPipe = count($this->_pipelineBuffer);
  567. if ($sizeofPipe === 0) {
  568. return;
  569. }
  570. $connection = $this->_redisClient->getConnection();
  571. $commands = &$this->_pipelineBuffer;
  572. foreach ($commands as $command) {
  573. $connection->writeCommand($command);
  574. }
  575. for ($i = 0; $i < $sizeofPipe; $i++) {
  576. $response = $connection->readResponse($commands[$i]);
  577. $this->_returnValues[] = ($response instanceof Iterator
  578. ? iterator_to_array($response)
  579. : $response
  580. );
  581. unset($commands[$i]);
  582. }
  583. $this->_pipelineBuffer = array();
  584. return $this;
  585. }
  586. private function setRunning($bool) {
  587. if ($bool == true && $this->_running == true) {
  588. throw new Predis_ClientException("This pipeline is already opened");
  589. }
  590. $this->_running = $bool;
  591. }
  592. public function execute($block = null) {
  593. if ($block && !is_callable($block)) {
  594. throw new RuntimeException('Argument passed must be a callable object');
  595. }
  596. // TODO: do not reuse previously executed pipelines
  597. $this->setRunning(true);
  598. $pipelineBlockException = null;
  599. try {
  600. if ($block !== null) {
  601. $block($this);
  602. }
  603. $this->flushPipeline();
  604. }
  605. catch (Exception $exception) {
  606. // TODO: client/server desync on ServerException
  607. $pipelineBlockException = $exception;
  608. }
  609. $this->setRunning(false);
  610. if ($pipelineBlockException !== null) {
  611. throw $pipelineBlockException;
  612. }
  613. return $this->_returnValues;
  614. }
  615. }
  616. class Predis_MultiExecBlock {
  617. private $_redisClient, $_commands, $_initialized, $_discarded;
  618. public function __construct(Predis_Client $redisClient) {
  619. $this->_initialized = false;
  620. $this->_discarded = false;
  621. $this->_redisClient = $redisClient;
  622. $this->_commands = array();
  623. }
  624. private function initialize() {
  625. if ($this->_initialized === false) {
  626. $this->_redisClient->multi();
  627. $this->_initialized = true;
  628. $this->_discarded = false;
  629. }
  630. }
  631. public function __call($method, $arguments) {
  632. $this->initialize();
  633. $command = $this->_redisClient->createCommand($method, $arguments);
  634. $response = $this->_redisClient->executeCommand($command);
  635. if (isset($response->queued)) {
  636. $this->_commands[] = $command;
  637. return $this;
  638. }
  639. else {
  640. $this->malformedServerResponse('The server did not respond with a QUEUED status reply');
  641. }
  642. }
  643. public function discard() {
  644. $this->_redisClient->discard();
  645. $this->_commands = array();
  646. $this->_initialized = false;
  647. $this->_discarded = true;
  648. }
  649. public function execute($block = null) {
  650. if ($block && !is_callable($block)) {
  651. throw new RuntimeException('Argument passed must be a callable object');
  652. }
  653. $blockException = null;
  654. $returnValues = array();
  655. try {
  656. if ($block !== null) {
  657. $block($this);
  658. }
  659. if ($this->_discarded === true) {
  660. return;
  661. }
  662. $execReply = (($reply = $this->_redisClient->exec()) instanceof Iterator
  663. ? iterator_to_array($reply)
  664. : $reply
  665. );
  666. $commands = &$this->_commands;
  667. $sizeofReplies = count($execReply);
  668. if ($sizeofReplies !== count($commands)) {
  669. $this->malformedServerResponse('Unexpected number of responses for a MultiExecBlock');
  670. }
  671. for ($i = 0; $i < $sizeofReplies; $i++) {
  672. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof Iterator
  673. ? iterator_to_array($execReply[$i])
  674. : $execReply[$i]
  675. );
  676. unset($commands[$i]);
  677. }
  678. }
  679. catch (Exception $exception) {
  680. $blockException = $exception;
  681. }
  682. if ($blockException !== null) {
  683. throw $blockException;
  684. }
  685. return $returnValues;
  686. }
  687. }
  688. /* ------------------------------------------------------------------------- */
  689. class Predis_ConnectionParameters {
  690. const DEFAULT_HOST = '127.0.0.1';
  691. const DEFAULT_PORT = 6379;
  692. const DEFAULT_TIMEOUT = 5;
  693. private $_parameters;
  694. public function __construct($parameters = null) {
  695. $parameters = $parameters !== null ? $parameters : array();
  696. $this->_parameters = is_array($parameters)
  697. ? self::filterConnectionParams($parameters)
  698. : self::parseURI($parameters);
  699. }
  700. private static function parseURI($uri) {
  701. $parsed = @parse_url($uri);
  702. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  703. throw new Predis_ClientException("Invalid URI: $uri");
  704. }
  705. if (array_key_exists('query', $parsed)) {
  706. $details = array();
  707. foreach (explode('&', $parsed['query']) as $kv) {
  708. list($k, $v) = explode('=', $kv);
  709. switch ($k) {
  710. case 'database':
  711. $details['database'] = $v;
  712. break;
  713. case 'password':
  714. $details['password'] = $v;
  715. break;
  716. case 'connection_async':
  717. $details['connection_async'] = $v;
  718. break;
  719. case 'connection_persistent':
  720. $details['connection_persistent'] = $v;
  721. break;
  722. case 'connection_timeout':
  723. $details['connection_timeout'] = $v;
  724. break;
  725. case 'read_write_timeout':
  726. $details['read_write_timeout'] = $v;
  727. break;
  728. case 'alias':
  729. $details['alias'] = $v;
  730. break;
  731. case 'weight':
  732. $details['weight'] = $v;
  733. break;
  734. }
  735. }
  736. $parsed = array_merge($parsed, $details);
  737. }
  738. return self::filterConnectionParams($parsed);
  739. }
  740. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  741. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  742. }
  743. private static function filterConnectionParams($parameters) {
  744. return array(
  745. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  746. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  747. 'database' => self::getParamOrDefault($parameters, 'database'),
  748. 'password' => self::getParamOrDefault($parameters, 'password'),
  749. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  750. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  751. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  752. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  753. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  754. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  755. );
  756. }
  757. public function __get($parameter) {
  758. return $this->_parameters[$parameter];
  759. }
  760. public function __isset($parameter) {
  761. return isset($this->_parameters[$parameter]);
  762. }
  763. }
  764. interface Predis_IDistributionAlgorithm {
  765. public function add($node, $weight = null);
  766. public function remove($node);
  767. public function get($key);
  768. public function generateKey($value);
  769. }
  770. interface Predis_IConnection {
  771. public function connect();
  772. public function disconnect();
  773. public function isConnected();
  774. public function writeCommand(Predis_Command $command);
  775. public function readResponse(Predis_Command $command);
  776. public function executeCommand(Predis_Command $command);
  777. }
  778. class Predis_Connection implements Predis_IConnection {
  779. private $_params, $_socket, $_initCmds, $_reader;
  780. public function __construct(Predis_ConnectionParameters $parameters, Predis_ResponseReader $reader = null) {
  781. $this->_params = $parameters;
  782. $this->_initCmds = array();
  783. $this->_reader = $reader !== null ? $reader : new Predis_ResponseReader();
  784. }
  785. public function __destruct() {
  786. if (!$this->_params->connection_persistent) {
  787. $this->disconnect();
  788. }
  789. }
  790. public function isConnected() {
  791. return is_resource($this->_socket);
  792. }
  793. public function connect() {
  794. if ($this->isConnected()) {
  795. throw new Predis_ClientException('Connection already estabilished');
  796. }
  797. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  798. $connectFlags = STREAM_CLIENT_CONNECT;
  799. if ($this->_params->connection_async) {
  800. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  801. }
  802. if ($this->_params->connection_persistent) {
  803. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  804. }
  805. $this->_socket = @stream_socket_client(
  806. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  807. );
  808. if (!$this->_socket) {
  809. $this->onCommunicationException(trim($errstr), $errno);
  810. }
  811. if (isset($this->_params->read_write_timeout)) {
  812. $timeoutSeconds = floor($this->_params->read_write_timeout);
  813. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  814. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  815. }
  816. if (count($this->_initCmds) > 0){
  817. $this->sendInitializationCommands();
  818. }
  819. }
  820. public function disconnect() {
  821. if ($this->isConnected()) {
  822. fclose($this->_socket);
  823. }
  824. }
  825. public function pushInitCommand(Predis_Command $command){
  826. $this->_initCmds[] = $command;
  827. }
  828. private function sendInitializationCommands() {
  829. foreach ($this->_initCmds as $command) {
  830. $this->writeCommand($command);
  831. }
  832. foreach ($this->_initCmds as $command) {
  833. $this->readResponse($command);
  834. }
  835. }
  836. private function onCommunicationException($message, $code = null) {
  837. Predis_Utilities_Shared::onCommunicationException(
  838. new Predis_CommunicationException($this, $message, $code)
  839. );
  840. }
  841. public function writeCommand(Predis_Command $command) {
  842. $this->writeBytes($command->invoke());
  843. }
  844. public function readResponse(Predis_Command $command) {
  845. $response = $this->_reader->read($this);
  846. $skipparse = isset($response->queued) || isset($response->error);
  847. return $skipparse ? $response : $command->parseResponse($response);
  848. }
  849. public function executeCommand(Predis_Command $command) {
  850. $this->writeCommand($command);
  851. if ($command->closesConnection()) {
  852. return $this->disconnect();
  853. }
  854. return $this->readResponse($command);
  855. }
  856. public function rawCommand($rawCommandData, $closesConnection = false) {
  857. $this->writeBytes($rawCommandData);
  858. if ($closesConnection) {
  859. $this->disconnect();
  860. return;
  861. }
  862. return $this->_reader->read($this);
  863. }
  864. public function writeBytes($value) {
  865. $socket = $this->getSocket();
  866. while (($length = strlen($value)) > 0) {
  867. $written = fwrite($socket, $value);
  868. if ($length === $written) {
  869. return true;
  870. }
  871. if ($written === false || $written === 0) {
  872. $this->onCommunicationException('Error while writing bytes to the server');
  873. }
  874. $value = substr($value, $written);
  875. }
  876. return true;
  877. }
  878. public function readBytes($length) {
  879. if ($length == 0) {
  880. throw new InvalidArgumentException('Length parameter must be greater than 0');
  881. }
  882. $socket = $this->getSocket();
  883. $value = '';
  884. do {
  885. $chunk = fread($socket, $length);
  886. if ($chunk === false || $chunk === '') {
  887. $this->onCommunicationException('Error while reading bytes from the server');
  888. }
  889. $value .= $chunk;
  890. }
  891. while (($length -= strlen($chunk)) > 0);
  892. return $value;
  893. }
  894. public function readLine() {
  895. $socket = $this->getSocket();
  896. $value = '';
  897. do {
  898. $chunk = fgets($socket);
  899. if ($chunk === false || strlen($chunk) == 0) {
  900. $this->onCommunicationException('Error while reading line from the server');
  901. }
  902. $value .= $chunk;
  903. }
  904. while (substr($value, -2) !== Predis_Protocol::NEWLINE);
  905. return substr($value, 0, -2);
  906. }
  907. public function getSocket() {
  908. if (!$this->isConnected()) {
  909. $this->connect();
  910. }
  911. return $this->_socket;
  912. }
  913. public function getResponseReader() {
  914. return $this->_reader;
  915. }
  916. public function getParameters() {
  917. return $this->_params;
  918. }
  919. public function __toString() {
  920. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  921. }
  922. }
  923. class Predis_ConnectionCluster implements Predis_IConnection, IteratorAggregate {
  924. private $_pool, $_distributor;
  925. public function __construct(Predis_IDistributionAlgorithm $distributor = null) {
  926. $this->_pool = array();
  927. $this->_distributor = $distributor !== null ? $distributor : new Predis_Utilities_HashRing();
  928. }
  929. public function isConnected() {
  930. foreach ($this->_pool as $connection) {
  931. if ($connection->isConnected()) {
  932. return true;
  933. }
  934. }
  935. return false;
  936. }
  937. public function connect() {
  938. foreach ($this->_pool as $connection) {
  939. $connection->connect();
  940. }
  941. }
  942. public function disconnect() {
  943. foreach ($this->_pool as $connection) {
  944. $connection->disconnect();
  945. }
  946. }
  947. public function add(Predis_Connection $connection) {
  948. $parameters = $connection->getParameters();
  949. if (isset($parameters->alias)) {
  950. $this->_pool[$parameters->alias] = $connection;
  951. }
  952. else {
  953. $this->_pool[] = $connection;
  954. }
  955. $this->_distributor->add($connection, $parameters->weight);
  956. }
  957. public function getConnection(Predis_Command $command) {
  958. if ($command->canBeHashed() === false) {
  959. throw new Predis_ClientException(
  960. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  961. );
  962. }
  963. return $this->_distributor->get($command->getHash($this->_distributor));
  964. }
  965. public function getConnectionById($id = null) {
  966. return $this->_pool[$id === null ? 0 : $id];
  967. }
  968. public function getIterator() {
  969. return new ArrayIterator($this->_pool);
  970. }
  971. public function writeCommand(Predis_Command $command) {
  972. $this->getConnection($command)->writeCommand($command);
  973. }
  974. public function readResponse(Predis_Command $command) {
  975. return $this->getConnection($command)->readResponse($command);
  976. }
  977. public function executeCommand(Predis_Command $command) {
  978. $connection = $this->getConnection($command);
  979. $connection->writeCommand($command);
  980. return $connection->readResponse($command);
  981. }
  982. }
  983. /* ------------------------------------------------------------------------- */
  984. abstract class Predis_RedisServerProfile {
  985. private static $_serverProfiles;
  986. private $_registeredCommands;
  987. public function __construct() {
  988. $this->_registeredCommands = $this->getSupportedCommands();
  989. }
  990. public abstract function getVersion();
  991. protected abstract function getSupportedCommands();
  992. public static function getDefault() {
  993. return self::get('default');
  994. }
  995. private static function predisServerProfiles() {
  996. return array(
  997. '1.2' => 'Predis_RedisServer_v1_2',
  998. '2.0' => 'Predis_RedisServer_v2_0',
  999. 'default' => 'Predis_RedisServer_v2_0',
  1000. 'dev' => 'Predis_RedisServer_vNext',
  1001. );
  1002. }
  1003. public static function registerProfile($profileClass, $aliases) {
  1004. if (!isset(self::$_serverProfiles)) {
  1005. self::$_serverProfiles = self::predisServerProfiles();
  1006. }
  1007. $profileReflection = new ReflectionClass($profileClass);
  1008. if (!$profileReflection->isSubclassOf('Predis_RedisServerProfile')) {
  1009. throw new Predis_ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1010. }
  1011. if (is_array($aliases)) {
  1012. foreach ($aliases as $alias) {
  1013. self::$_serverProfiles[$alias] = $profileClass;
  1014. }
  1015. }
  1016. else {
  1017. self::$_serverProfiles[$aliases] = $profileClass;
  1018. }
  1019. }
  1020. public static function get($version) {
  1021. if (!isset(self::$_serverProfiles)) {
  1022. self::$_serverProfiles = self::predisServerProfiles();
  1023. }
  1024. if (!isset(self::$_serverProfiles[$version])) {
  1025. throw new Predis_ClientException("Unknown server profile: $version");
  1026. }
  1027. $profile = self::$_serverProfiles[$version];
  1028. return new $profile();
  1029. }
  1030. public function compareWith($version, $operator = null) {
  1031. // one could expect that PHP's version_compare would behave
  1032. // the same way if invoked with 2 arguments or 3 arguments
  1033. // with the third being NULL, but it is not like that.
  1034. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  1035. // we might need to revise the behavior of this method.
  1036. return ($operator === null
  1037. ? version_compare($this, $version)
  1038. : version_compare($this, $version, $operator)
  1039. );
  1040. }
  1041. public function supportsCommand($command) {
  1042. return isset($this->_registeredCommands[$command]);
  1043. }
  1044. public function createCommand($method, $arguments = array()) {
  1045. if (!isset($this->_registeredCommands[$method])) {
  1046. throw new Predis_ClientException("'$method' is not a registered Redis command");
  1047. }
  1048. $commandClass = $this->_registeredCommands[$method];
  1049. $command = new $commandClass();
  1050. $command->setArgumentsArray($arguments);
  1051. return $command;
  1052. }
  1053. public function registerCommands(Array $commands) {
  1054. foreach ($commands as $command => $aliases) {
  1055. $this->registerCommand($command, $aliases);
  1056. }
  1057. }
  1058. public function registerCommand($command, $aliases) {
  1059. $commandReflection = new ReflectionClass($command);
  1060. if (!$commandReflection->isSubclassOf('Predis_Command')) {
  1061. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1062. }
  1063. if (is_array($aliases)) {
  1064. foreach ($aliases as $alias) {
  1065. $this->_registeredCommands[$alias] = $command;
  1066. }
  1067. }
  1068. else {
  1069. $this->_registeredCommands[$aliases] = $command;
  1070. }
  1071. }
  1072. public function __toString() {
  1073. return $this->getVersion();
  1074. }
  1075. }
  1076. class Predis_RedisServer_v1_2 extends Predis_RedisServerProfile {
  1077. public function getVersion() { return '1.2'; }
  1078. public function getSupportedCommands() {
  1079. return array(
  1080. /* miscellaneous commands */
  1081. 'ping' => 'Predis_Commands_Ping',
  1082. 'echo' => 'Predis_Commands_DoEcho',
  1083. 'auth' => 'Predis_Commands_Auth',
  1084. /* connection handling */
  1085. 'quit' => 'Predis_Commands_Quit',
  1086. /* commands operating on string values */
  1087. 'set' => 'Predis_Commands_Set',
  1088. 'setnx' => 'Predis_Commands_SetPreserve',
  1089. 'setPreserve' => 'Predis_Commands_SetPreserve',
  1090. 'mset' => 'Predis_Commands_SetMultiple',
  1091. 'setMultiple' => 'Predis_Commands_SetMultiple',
  1092. 'msetnx' => 'Predis_Commands_SetMultiplePreserve',
  1093. 'setMultiplePreserve' => 'Predis_Commands_SetMultiplePreserve',
  1094. 'get' => 'Predis_Commands_Get',
  1095. 'mget' => 'Predis_Commands_GetMultiple',
  1096. 'getMultiple' => 'Predis_Commands_GetMultiple',
  1097. 'getset' => 'Predis_Commands_GetSet',
  1098. 'getSet' => 'Predis_Commands_GetSet',
  1099. 'incr' => 'Predis_Commands_Increment',
  1100. 'increment' => 'Predis_Commands_Increment',
  1101. 'incrby' => 'Predis_Commands_IncrementBy',
  1102. 'incrementBy' => 'Predis_Commands_IncrementBy',
  1103. 'decr' => 'Predis_Commands_Decrement',
  1104. 'decrement' => 'Predis_Commands_Decrement',
  1105. 'decrby' => 'Predis_Commands_DecrementBy',
  1106. 'decrementBy' => 'Predis_Commands_DecrementBy',
  1107. 'exists' => 'Predis_Commands_Exists',
  1108. 'del' => 'Predis_Commands_Delete',
  1109. 'delete' => 'Predis_Commands_Delete',
  1110. 'type' => 'Predis_Commands_Type',
  1111. /* commands operating on the key space */
  1112. 'keys' => 'Predis_Commands_Keys',
  1113. 'randomkey' => 'Predis_Commands_RandomKey',
  1114. 'randomKey' => 'Predis_Commands_RandomKey',
  1115. 'rename' => 'Predis_Commands_Rename',
  1116. 'renamenx' => 'Predis_Commands_RenamePreserve',
  1117. 'renamePreserve' => 'Predis_Commands_RenamePreserve',
  1118. 'expire' => 'Predis_Commands_Expire',
  1119. 'expireat' => 'Predis_Commands_ExpireAt',
  1120. 'expireAt' => 'Predis_Commands_ExpireAt',
  1121. 'dbsize' => 'Predis_Commands_DatabaseSize',
  1122. 'databaseSize' => 'Predis_Commands_DatabaseSize',
  1123. 'ttl' => 'Predis_Commands_TimeToLive',
  1124. 'timeToLive' => 'Predis_Commands_TimeToLive',
  1125. /* commands operating on lists */
  1126. 'rpush' => 'Predis_Commands_ListPushTail',
  1127. 'pushTail' => 'Predis_Commands_ListPushTail',
  1128. 'lpush' => 'Predis_Commands_ListPushHead',
  1129. 'pushHead' => 'Predis_Commands_ListPushHead',
  1130. 'llen' => 'Predis_Commands_ListLength',
  1131. 'listLength' => 'Predis_Commands_ListLength',
  1132. 'lrange' => 'Predis_Commands_ListRange',
  1133. 'listRange' => 'Predis_Commands_ListRange',
  1134. 'ltrim' => 'Predis_Commands_ListTrim',
  1135. 'listTrim' => 'Predis_Commands_ListTrim',
  1136. 'lindex' => 'Predis_Commands_ListIndex',
  1137. 'listIndex' => 'Predis_Commands_ListIndex',
  1138. 'lset' => 'Predis_Commands_ListSet',
  1139. 'listSet' => 'Predis_Commands_ListSet',
  1140. 'lrem' => 'Predis_Commands_ListRemove',
  1141. 'listRemove' => 'Predis_Commands_ListRemove',
  1142. 'lpop' => 'Predis_Commands_ListPopFirst',
  1143. 'popFirst' => 'Predis_Commands_ListPopFirst',
  1144. 'rpop' => 'Predis_Commands_ListPopLast',
  1145. 'popLast' => 'Predis_Commands_ListPopLast',
  1146. 'rpoplpush' => 'Predis_Commands_ListPopLastPushHead',
  1147. 'listPopLastPushHead' => 'Predis_Commands_ListPopLastPushHead',
  1148. /* commands operating on sets */
  1149. 'sadd' => 'Predis_Commands_SetAdd',
  1150. 'setAdd' => 'Predis_Commands_SetAdd',
  1151. 'srem' => 'Predis_Commands_SetRemove',
  1152. 'setRemove' => 'Predis_Commands_SetRemove',
  1153. 'spop' => 'Predis_Commands_SetPop',
  1154. 'setPop' => 'Predis_Commands_SetPop',
  1155. 'smove' => 'Predis_Commands_SetMove',
  1156. 'setMove' => 'Predis_Commands_SetMove',
  1157. 'scard' => 'Predis_Commands_SetCardinality',
  1158. 'setCardinality' => 'Predis_Commands_SetCardinality',
  1159. 'sismember' => 'Predis_Commands_SetIsMember',
  1160. 'setIsMember' => 'Predis_Commands_SetIsMember',
  1161. 'sinter' => 'Predis_Commands_SetIntersection',
  1162. 'setIntersection' => 'Predis_Commands_SetIntersection',
  1163. 'sinterstore' => 'Predis_Commands_SetIntersectionStore',
  1164. 'setIntersectionStore' => 'Predis_Commands_SetIntersectionStore',
  1165. 'sunion' => 'Predis_Commands_SetUnion',
  1166. 'setUnion' => 'Predis_Commands_SetUnion',
  1167. 'sunionstore' => 'Predis_Commands_SetUnionStore',
  1168. 'setUnionStore' => 'Predis_Commands_SetUnionStore',
  1169. 'sdiff' => 'Predis_Commands_SetDifference',
  1170. 'setDifference' => 'Predis_Commands_SetDifference',
  1171. 'sdiffstore' => 'Predis_Commands_SetDifferenceStore',
  1172. 'setDifferenceStore' => 'Predis_Commands_SetDifferenceStore',
  1173. 'smembers' => 'Predis_Commands_SetMembers',
  1174. 'setMembers' => 'Predis_Commands_SetMembers',
  1175. 'srandmember' => 'Predis_Commands_SetRandomMember',
  1176. 'setRandomMember' => 'Predis_Commands_SetRandomMember',
  1177. /* commands operating on sorted sets */
  1178. 'zadd' => 'Predis_Commands_ZSetAdd',
  1179. 'zsetAdd' => 'Predis_Commands_ZSetAdd',
  1180. 'zincrby' => 'Predis_Commands_ZSetIncrementBy',
  1181. 'zsetIncrementBy' => 'Predis_Commands_ZSetIncrementBy',
  1182. 'zrem' => 'Predis_Commands_ZSetRemove',
  1183. 'zsetRemove' => 'Predis_Commands_ZSetRemove',
  1184. 'zrange' => 'Predis_Commands_ZSetRange',
  1185. 'zsetRange' => 'Predis_Commands_ZSetRange',
  1186. 'zrevrange' => 'Predis_Commands_ZSetReverseRange',
  1187. 'zsetReverseRange' => 'Predis_Commands_ZSetReverseRange',
  1188. 'zrangebyscore' => 'Predis_Commands_ZSetRangeByScore',
  1189. 'zsetRangeByScore' => 'Predis_Commands_ZSetRangeByScore',
  1190. 'zcard' => 'Predis_Commands_ZSetCardinality',
  1191. 'zsetCardinality' => 'Predis_Commands_ZSetCardinality',
  1192. 'zscore' => 'Predis_Commands_ZSetScore',
  1193. 'zsetScore' => 'Predis_Commands_ZSetScore',
  1194. 'zremrangebyscore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  1195. 'zsetRemoveRangeByScore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  1196. /* multiple databases handling commands */
  1197. 'select' => 'Predis_Commands_SelectDatabase',
  1198. 'selectDatabase' => 'Predis_Commands_SelectDatabase',
  1199. 'move' => 'Predis_Commands_MoveKey',
  1200. 'moveKey' => 'Predis_Commands_MoveKey',
  1201. 'flushdb' => 'Predis_Commands_FlushDatabase',
  1202. 'flushDatabase' => 'Predis_Commands_FlushDatabase',
  1203. 'flushall' => 'Predis_Commands_FlushAll',
  1204. 'flushDatabases' => 'Predis_Commands_FlushAll',
  1205. /* sorting */
  1206. 'sort' => 'Predis_Commands_Sort',
  1207. /* remote server control commands */
  1208. 'info' => 'Predis_Commands_Info',
  1209. 'slaveof' => 'Predis_Commands_SlaveOf',
  1210. 'slaveOf' => 'Predis_Commands_SlaveOf',
  1211. /* persistence control commands */
  1212. 'save' => 'Predis_Commands_Save',
  1213. 'bgsave' => 'Predis_Commands_BackgroundSave',
  1214. 'backgroundSave' => 'Predis_Commands_BackgroundSave',
  1215. 'lastsave' => 'Predis_Commands_LastSave',
  1216. 'lastSave' => 'Predis_Commands_LastSave',
  1217. 'shutdown' => 'Predis_Commands_Shutdown',
  1218. 'bgrewriteaof' => 'Predis_Commands_BackgroundRewriteAppendOnlyFile',
  1219. 'backgroundRewriteAppendOnlyFile' => 'Predis_Commands_BackgroundRewriteAppendOnlyFile',
  1220. );
  1221. }
  1222. }
  1223. class Predis_RedisServer_v2_0 extends Predis_RedisServer_v1_2 {
  1224. public function getVersion() { return '2.0'; }
  1225. public function getSupportedCommands() {
  1226. return array_merge(parent::getSupportedCommands(), array(
  1227. /* transactions */
  1228. 'multi' => 'Predis_Commands_Multi',
  1229. 'exec' => 'Predis_Commands_Exec',
  1230. 'discard' => 'Predis_Commands_Discard',
  1231. /* commands operating on string values */
  1232. 'setex' => 'Predis_Commands_SetExpire',
  1233. 'setExpire' => 'Predis_Commands_SetExpire',
  1234. 'append' => 'Predis_Commands_Append',
  1235. 'substr' => 'Predis_Commands_Substr',
  1236. /* commands operating on lists */
  1237. 'blpop' => 'Predis_Commands_ListPopFirstBlocking',
  1238. 'popFirstBlocking' => 'Predis_Commands_ListPopFirstBlocking',
  1239. 'brpop' => 'Predis_Commands_ListPopLastBlocking',
  1240. 'popLastBlocking' => 'Predis_Commands_ListPopLastBlocking',
  1241. /* commands operating on sorted sets */
  1242. 'zunionstore' => 'Predis_Commands_ZSetUnionStore',
  1243. 'zsetUnionStore' => 'Predis_Commands_ZSetUnionStore',
  1244. 'zinterstore' => 'Predis_Commands_ZSetIntersectionStore',
  1245. 'zsetIntersectionStore' => 'Predis_Commands_ZSetIntersectionStore',
  1246. 'zcount' => 'Predis_Commands_ZSetCount',
  1247. 'zsetCount' => 'Predis_Commands_ZSetCount',
  1248. 'zrank' => 'Predis_Commands_ZSetRank',
  1249. 'zsetRank' => 'Predis_Commands_ZSetRank',
  1250. 'zrevrank' => 'Predis_Commands_ZSetReverseRank',
  1251. 'zsetReverseRank' => 'Predis_Commands_ZSetReverseRank',
  1252. 'zremrangebyrank' => 'Predis_Commands_ZSetRemoveRangeByRank',
  1253. 'zsetRemoveRangeByRank' => 'Predis_Commands_ZSetRemoveRangeByRank',
  1254. /* commands operating on hashes */
  1255. 'hset' => 'Predis_Commands_HashSet',
  1256. 'hashSet' => 'Predis_Commands_HashSet',
  1257. 'hsetnx' => 'Predis_Commands_HashSetPreserve',
  1258. 'hashSetPreserve' => 'Predis_Commands_HashSetPreserve',
  1259. 'hmset' => 'Predis_Commands_HashSetMultiple',
  1260. 'hashSetMultiple' => 'Predis_Commands_HashSetMultiple',
  1261. 'hincrby' => 'Predis_Commands_HashIncrementBy',
  1262. 'hashIncrementBy' => 'Predis_Commands_HashIncrementBy',
  1263. 'hget' => 'Predis_Commands_HashGet',
  1264. 'hashGet' => 'Predis_Commands_HashGet',
  1265. 'hmget' => 'Predis_Commands_HashGetMultiple',
  1266. 'hashGetMultiple' => 'Predis_Commands_HashGetMultiple',
  1267. 'hdel' => 'Predis_Commands_HashDelete',
  1268. 'hashDelete' => 'Predis_Commands_HashDelete',
  1269. 'hexists' => 'Predis_Commands_HashExists',
  1270. 'hashExists' => 'Predis_Commands_HashExists',
  1271. 'hlen' => 'Predis_Commands_HashLength',
  1272. 'hashLength' => 'Predis_Commands_HashLength',
  1273. 'hkeys' => 'Predis_Commands_HashKeys',
  1274. 'hashKeys' => 'Predis_Commands_HashKeys',
  1275. 'hvals' => 'Predis_Commands_HashValues',
  1276. 'hashValues' => 'Predis_Commands_HashValues',
  1277. 'hgetall' => 'Predis_Commands_HashGetAll',
  1278. 'hashGetAll' => 'Predis_Commands_HashGetAll',
  1279. /* publish - subscribe */
  1280. 'subscribe' => 'Predis_Commands_Subscribe',
  1281. 'unsubscribe' => 'Predis_Commands_Unsubscribe',
  1282. 'psubscribe' => 'Predis_Commands_SubscribeByPattern',
  1283. 'punsubscribe' => 'Predis_Commands_UnsubscribeByPattern',
  1284. 'publish' => 'Predis_Commands_Publish',
  1285. /* remote server control commands */
  1286. 'config' => 'Predis_Commands_Config',
  1287. 'configuration' => 'Predis_Commands_Config',
  1288. ));
  1289. }
  1290. }
  1291. class Predis_RedisServer_vNext extends Predis_RedisServer_v2_0 {
  1292. public function getVersion() { return '2.1'; }
  1293. }
  1294. /* ------------------------------------------------------------------------- */
  1295. class Predis_Utilities_Shared {
  1296. public static function onCommunicationException(Predis_CommunicationException $exception) {
  1297. if ($exception->shouldResetConnection()) {
  1298. $connection = $exception->getConnection();
  1299. if ($connection->isConnected()) {
  1300. $connection->disconnect();
  1301. }
  1302. }
  1303. throw $exception;
  1304. }
  1305. }
  1306. class Predis_Utilities_HashRing implements Predis_IDistributionAlgorithm {
  1307. const DEFAULT_REPLICAS = 128;
  1308. const DEFAULT_WEIGHT = 100;
  1309. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1310. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1311. $this->_replicas = $replicas;
  1312. $this->_nodes = array();
  1313. }
  1314. public function add($node, $weight = null) {
  1315. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1316. // last wins, thus the order in which nodes are added is significant.
  1317. // TODO: self::DEFAULT_WEIGHT does not work for inherited classes that
  1318. // override the DEFAULT_WEIGHT constant.
  1319. $this->_nodes[] = array(
  1320. 'object' => $node,
  1321. 'weight' => (int) ($weight !== null ? $weight : self::DEFAULT_WEIGHT),
  1322. );
  1323. $this->reset();
  1324. }
  1325. public function remove($node) {
  1326. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1327. // scratch, in order to reassign possible hashes with collisions to the
  1328. // right node according to the order in which they were added in the
  1329. // first place.
  1330. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1331. if ($this->_nodes[$i]['object'] === $node) {
  1332. array_splice($this->_nodes, $i, 1);
  1333. $this->reset();
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. private function reset() {
  1339. unset($this->_ring);
  1340. unset($this->_ringKeys);
  1341. unset($this->_ringKeysCount);
  1342. }
  1343. private function isInitialized() {
  1344. return isset($this->_ringKeys);
  1345. }
  1346. private function computeTotalWeight() {
  1347. $totalWeight = 0;
  1348. foreach ($this->_nodes as $node) {
  1349. $totalWeight += $node['weight'];
  1350. }
  1351. return $totalWeight;
  1352. }
  1353. private function initialize() {
  1354. if ($this->isInitialized()) {
  1355. return;
  1356. }
  1357. if (count($this->_nodes) === 0) {
  1358. throw new LogicException('Cannot initialize empty hashring');
  1359. }
  1360. $this->_ring = array();
  1361. $totalWeight = $this->computeTotalWeight();
  1362. $nodesCount = count($this->_nodes);
  1363. foreach ($this->_nodes as $node) {
  1364. $weightRatio = $node['weight'] / $totalWeight;
  1365. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1366. }
  1367. ksort($this->_ring, SORT_NUMERIC);
  1368. $this->_ringKeys = array_keys($this->_ring);
  1369. $this->_ringKeysCount = count($this->_ringKeys);
  1370. }
  1371. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1372. $nodeObject = $node['object'];
  1373. $nodeHash = (string) $nodeObject;
  1374. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1375. for ($i = 0; $i < $replicas; $i++) {
  1376. $key = crc32("$nodeHash:$i");
  1377. $ring[$key] = $nodeObject;
  1378. }
  1379. }
  1380. public function generateKey($value) {
  1381. return crc32($value);
  1382. }
  1383. public function get($key) {
  1384. return $this->_ring[$this->getNodeKey($key)];
  1385. }
  1386. private function getNodeKey($key) {
  1387. $this->initialize();
  1388. $ringKeys = $this->_ringKeys;
  1389. $upper = $this->_ringKeysCount - 1;
  1390. $lower = 0;
  1391. while ($lower <= $upper) {
  1392. $index = ($lower + $upper) >> 1;
  1393. $item = $ringKeys[$index];
  1394. if ($item > $key) {
  1395. $upper = $index - 1;
  1396. }
  1397. else if ($item < $key) {
  1398. $lower = $index + 1;
  1399. }
  1400. else {
  1401. return $item;
  1402. }
  1403. }
  1404. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1405. }
  1406. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1407. // NOTE: binary search for the last item in _ringkeys with a value
  1408. // less or equal to the key. If no such item exists, return the
  1409. // last item.
  1410. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1411. }
  1412. }
  1413. class Predis_Utilities_KetamaPureRing extends Predis_Utilities_HashRing {
  1414. const DEFAULT_REPLICAS = 160;
  1415. public function __construct() {
  1416. parent::__construct(self::DEFAULT_REPLICAS);
  1417. }
  1418. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1419. $nodeObject = $node['object'];
  1420. $nodeHash = (string) $nodeObject;
  1421. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1422. for ($i = 0; $i < $replicas; $i++) {
  1423. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1424. foreach ($unpackedDigest as $key) {
  1425. $ring[$key] = $nodeObject;
  1426. }
  1427. }
  1428. }
  1429. public function generateKey($value) {
  1430. $hash = unpack('V', md5($value, true));
  1431. return $hash[1];
  1432. }
  1433. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1434. // NOTE: binary search for the first item in _ringkeys with a value
  1435. // greater or equal to the key. If no such item exists, return the
  1436. // first item.
  1437. return $lower < $ringKeysCount ? $lower : 0;
  1438. }
  1439. }
  1440. abstract class Predis_Utilities_MultiBulkResponseIteratorBase implements Iterator, Countable {
  1441. protected $_position, $_current, $_replySize;
  1442. public function rewind() {
  1443. // NOOP
  1444. }
  1445. public function current() {
  1446. return $this->_current;
  1447. }
  1448. public function key() {
  1449. return $this->_position;
  1450. }
  1451. public function next() {
  1452. if (++$this->_position < $this->_replySize) {
  1453. $this->_current = $this->getValue();
  1454. }
  1455. return $this->_position;
  1456. }
  1457. public function valid() {
  1458. return $this->_position < $this->_replySize;
  1459. }
  1460. public function count() {
  1461. // NOTE: use count if you want to get the size of the current multi-bulk
  1462. // response without using iterator_count (which actually consumes
  1463. // our iterator to calculate the size, and we cannot perform a rewind)
  1464. return $this->_replySize;
  1465. }
  1466. protected abstract function getValue();
  1467. }
  1468. class Predis_Utilities_MultiBulkResponseIterator extends Predis_Utilities_MultiBulkResponseIteratorBase {
  1469. private $_connection;
  1470. public function __construct(Predis_Connection $connection, $size) {
  1471. $this->_connection = $connection;
  1472. $this->_reader = $connection->getResponseReader();
  1473. $this->_position = 0;
  1474. $this->_current = $size > 0 ? $this->getValue() : null;
  1475. $this->_replySize = $size;
  1476. }
  1477. public function __destruct() {
  1478. // when the iterator is garbage-collected (e.g. it goes out of the
  1479. // scope of a foreach) but it has not reached its end, we must sync
  1480. // the client with the queued elements that have not been read from
  1481. // the connection with the server.
  1482. $this->sync();
  1483. }
  1484. public function sync() {
  1485. while ($this->valid()) {
  1486. $this->next();
  1487. }
  1488. }
  1489. protected function getValue() {
  1490. return $this->_reader->read($this->_connection);
  1491. }
  1492. }
  1493. class Predis_Utilities_MultiBulkResponseKVIterator extends Predis_Utilities_MultiBulkResponseIteratorBase {
  1494. private $_iterator;
  1495. public function __construct(Predis_Utilities_MultiBulkResponseIterator $iterator) {
  1496. $virtualSize = count($iterator) / 2;
  1497. $this->_iterator = $iterator;
  1498. $this->_position = 0;
  1499. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1500. $this->_replySize = $virtualSize;
  1501. }
  1502. public function __destruct() {
  1503. $this->_iterator->sync();
  1504. }
  1505. protected function getValue() {
  1506. $k = $this->_iterator->current();
  1507. $this->_iterator->next();
  1508. $v = $this->_iterator->current();
  1509. $this->_iterator->next();
  1510. return array($k, $v);
  1511. }
  1512. }
  1513. /* ------------------------------------------------------------------------- */
  1514. /* miscellaneous commands */
  1515. class Predis_Commands_Ping extends Predis_MultiBulkCommand {
  1516. public function canBeHashed() { return false; }
  1517. public function getCommandId() { return 'PING'; }
  1518. public function parseResponse($data) {
  1519. return $data === 'PONG' ? true : false;
  1520. }
  1521. }
  1522. class Predis_Commands_DoEcho extends Predis_MultiBulkCommand {
  1523. public function canBeHashed() { return false; }
  1524. public function getCommandId() { return 'ECHO'; }
  1525. }
  1526. class Predis_Commands_Auth extends Predis_MultiBulkCommand {
  1527. public function canBeHashed() { return false; }
  1528. public function getCommandId() { return 'AUTH'; }
  1529. }
  1530. /* connection handling */
  1531. class Predis_Commands_Quit extends Predis_MultiBulkCommand {
  1532. public function canBeHashed() { return false; }
  1533. public function getCommandId() { return 'QUIT'; }
  1534. public function closesConnection() { return true; }
  1535. }
  1536. /* commands operating on string values */
  1537. class Predis_Commands_Set extends Predis_MultiBulkCommand {
  1538. public function getCommandId() { return 'SET'; }
  1539. }
  1540. class Predis_Commands_SetExpire extends Predis_MultiBulkCommand {
  1541. public function getCommandId() { return 'SETEX'; }
  1542. }
  1543. class Predis_Commands_SetPreserve extends Predis_MultiBulkCommand {
  1544. public function getCommandId() { return 'SETNX'; }
  1545. public function parseResponse($data) { return (bool) $data; }
  1546. }
  1547. class Predis_Commands_SetMultiple extends Predis_MultiBulkCommand {
  1548. public function canBeHashed() { return false; }
  1549. public function getCommandId() { return 'MSET'; }
  1550. public function filterArguments(Array $arguments) {
  1551. if (count($arguments) === 1 && is_array($arguments[0])) {
  1552. $flattenedKVs = array();
  1553. $args = &$arguments[0];
  1554. foreach ($args as $k => $v) {
  1555. $flattenedKVs[] = $k;
  1556. $flattenedKVs[] = $v;
  1557. }
  1558. return $flattenedKVs;
  1559. }
  1560. return $arguments;
  1561. }
  1562. }
  1563. class Predis_Commands_SetMultiplePreserve extends Predis_Commands_SetMultiple {
  1564. public function canBeHashed() { return false; }
  1565. public function getCommandId() { return 'MSETNX'; }
  1566. public function parseResponse($data) { return (bool) $data; }
  1567. }
  1568. class Predis_Commands_Get extends Predis_MultiBulkCommand {
  1569. public function getCommandId() { return 'GET'; }
  1570. }
  1571. class Predis_Commands_GetMultiple extends Predis_MultiBulkCommand {
  1572. public function canBeHashed() { return false; }
  1573. public function getCommandId() { return 'MGET'; }
  1574. }
  1575. class Predis_Commands_GetSet extends Predis_MultiBulkCommand {
  1576. public function getCommandId() { return 'GETSET'; }
  1577. }
  1578. class Predis_Commands_Increment extends Predis_MultiBulkCommand {
  1579. public function getCommandId() { return 'INCR'; }
  1580. }
  1581. class Predis_Commands_IncrementBy extends Predis_MultiBulkCommand {
  1582. public function getCommandId() { return 'INCRBY'; }
  1583. }
  1584. class Predis_Commands_Decrement extends Predis_MultiBulkCommand {
  1585. public function getCommandId() { return 'DECR'; }
  1586. }
  1587. class Predis_Commands_DecrementBy extends Predis_MultiBulkCommand {
  1588. public function getCommandId() { return 'DECRBY'; }
  1589. }
  1590. class Predis_Commands_Exists extends Predis_MultiBulkCommand {
  1591. public function getCommandId() { return 'EXISTS'; }
  1592. public function parseResponse($data) { return (bool) $data; }
  1593. }
  1594. class Predis_Commands_Delete extends Predis_MultiBulkCommand {
  1595. public function getCommandId() { return 'DEL'; }
  1596. }
  1597. class Predis_Commands_Type extends Predis_MultiBulkCommand {
  1598. public function getCommandId() { return 'TYPE'; }
  1599. }
  1600. class Predis_Commands_Append extends Predis_MultiBulkCommand {
  1601. public function getCommandId() { return 'APPEND'; }
  1602. }
  1603. class Predis_Commands_Substr extends Predis_MultiBulkCommand {
  1604. public function getCommandId() { return 'SUBSTR'; }
  1605. }
  1606. /* commands operating on the key space */
  1607. class Predis_Commands_Keys extends Predis_MultiBulkCommand {
  1608. public function canBeHashed() { return false; }
  1609. public function getCommandId() { return 'KEYS'; }
  1610. public function parseResponse($data) {
  1611. // TODO: is this behaviour correct?
  1612. if (is_array($data) || $data instanceof Iterator) {
  1613. return $data;
  1614. }
  1615. return strlen($data) > 0 ? explode(' ', $data) : array();
  1616. }
  1617. }
  1618. class Predis_Commands_RandomKey extends Predis_MultiBulkCommand {
  1619. public function canBeHashed() { return false; }
  1620. public function getCommandId() { return 'RANDOMKEY'; }
  1621. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1622. }
  1623. class Predis_Commands_Rename extends Predis_MultiBulkCommand {
  1624. public function canBeHashed() { return false; }
  1625. public function getCommandId() { return 'RENAME'; }
  1626. }
  1627. class Predis_Commands_RenamePreserve extends Predis_MultiBulkCommand {
  1628. public function canBeHashed() { return false; }
  1629. public function getCommandId() { return 'RENAMENX'; }
  1630. public function parseResponse($data) { return (bool) $data; }
  1631. }
  1632. class Predis_Commands_Expire extends Predis_MultiBulkCommand {
  1633. public function getCommandId() { return 'EXPIRE'; }
  1634. public function parseResponse($data) { return (bool) $data; }
  1635. }
  1636. class Predis_Commands_ExpireAt extends Predis_MultiBulkCommand {
  1637. public function getCommandId() { return 'EXPIREAT'; }
  1638. public function parseResponse($data) { return (bool) $data; }
  1639. }
  1640. class Predis_Commands_DatabaseSize extends Predis_MultiBulkCommand {
  1641. public function canBeHashed() { return false; }
  1642. public function getCommandId() { return 'DBSIZE'; }
  1643. }
  1644. class Predis_Commands_TimeToLive extends Predis_MultiBulkCommand {
  1645. public function getCommandId() { return 'TTL'; }
  1646. }
  1647. /* commands operating on lists */
  1648. class Predis_Commands_ListPushTail extends Predis_MultiBulkCommand {
  1649. public function getCommandId() { return 'RPUSH'; }
  1650. }
  1651. class Predis_Commands_ListPushHead extends Predis_MultiBulkCommand {
  1652. public function getCommandId() { return 'LPUSH'; }
  1653. }
  1654. class Predis_Commands_ListLength extends Predis_MultiBulkCommand {
  1655. public function getCommandId() { return 'LLEN'; }
  1656. }
  1657. class Predis_Commands_ListRange extends Predis_MultiBulkCommand {
  1658. public function getCommandId() { return 'LRANGE'; }
  1659. }
  1660. class Predis_Commands_ListTrim extends Predis_MultiBulkCommand {
  1661. public function getCommandId() { return 'LTRIM'; }
  1662. }
  1663. class Predis_Commands_ListIndex extends Predis_MultiBulkCommand {
  1664. public function getCommandId() { return 'LINDEX'; }
  1665. }
  1666. class Predis_Commands_ListSet extends Predis_MultiBulkCommand {
  1667. public function getCommandId() { return 'LSET'; }
  1668. }
  1669. class Predis_Commands_ListRemove extends Predis_MultiBulkCommand {
  1670. public function getCommandId() { return 'LREM'; }
  1671. }
  1672. class Predis_Commands_ListPopLastPushHead extends Predis_MultiBulkCommand {
  1673. public function getCommandId() { return 'RPOPLPUSH'; }
  1674. }
  1675. class Predis_Commands_ListPopLastPushHeadBulk extends Predis_MultiBulkCommand {
  1676. public function getCommandId() { return 'RPOPLPUSH'; }
  1677. }
  1678. class Predis_Commands_ListPopFirst extends Predis_MultiBulkCommand {
  1679. public function getCommandId() { return 'LPOP'; }
  1680. }
  1681. class Predis_Commands_ListPopLast extends Predis_MultiBulkCommand {
  1682. public function getCommandId() { return 'RPOP'; }
  1683. }
  1684. class Predis_Commands_ListPopFirstBlocking extends Predis_MultiBulkCommand {
  1685. public function getCommandId() { return 'BLPOP'; }
  1686. }
  1687. class Predis_Commands_ListPopLastBlocking extends Predis_MultiBulkCommand {
  1688. public function getCommandId() { return 'BRPOP'; }
  1689. }
  1690. /* commands operating on sets */
  1691. class Predis_Commands_SetAdd extends Predis_MultiBulkCommand {
  1692. public function getCommandId() { return 'SADD'; }
  1693. public function parseResponse($data) { return (bool) $data; }
  1694. }
  1695. class Predis_Commands_SetRemove extends Predis_MultiBulkCommand {
  1696. public function getCommandId() { return 'SREM'; }
  1697. public function parseResponse($data) { return (bool) $data; }
  1698. }
  1699. class Predis_Commands_SetPop extends Predis_MultiBulkCommand {
  1700. public function getCommandId() { return 'SPOP'; }
  1701. }
  1702. class Predis_Commands_SetMove extends Predis_MultiBulkCommand {
  1703. public function canBeHashed() { return false; }
  1704. public function getCommandId() { return 'SMOVE'; }
  1705. public function parseResponse($data) { return (bool) $data; }
  1706. }
  1707. class Predis_Commands_SetCardinality extends Predis_MultiBulkCommand {
  1708. public function getCommandId() { return 'SCARD'; }
  1709. }
  1710. class Predis_Commands_SetIsMember extends Predis_MultiBulkCommand {
  1711. public function getCommandId() { return 'SISMEMBER'; }
  1712. public function parseResponse($data) { return (bool) $data; }
  1713. }
  1714. class Predis_Commands_SetIntersection extends Predis_MultiBulkCommand {
  1715. public function getCommandId() { return 'SINTER'; }
  1716. }
  1717. class Predis_Commands_SetIntersectionStore extends Predis_MultiBulkCommand {
  1718. public function getCommandId() { return 'SINTERSTORE'; }
  1719. }
  1720. class Predis_Commands_SetUnion extends Predis_MultiBulkCommand {
  1721. public function getCommandId() { return 'SUNION'; }
  1722. }
  1723. class Predis_Commands_SetUnionStore extends Predis_MultiBulkCommand {
  1724. public function getCommandId() { return 'SUNIONSTORE'; }
  1725. }
  1726. class Predis_Commands_SetDifference extends Predis_MultiBulkCommand {
  1727. public function getCommandId() { return 'SDIFF'; }
  1728. }
  1729. class Predis_Commands_SetDifferenceStore extends Predis_MultiBulkCommand {
  1730. public function getCommandId() { return 'SDIFFSTORE'; }
  1731. }
  1732. class Predis_Commands_SetMembers extends Predis_MultiBulkCommand {
  1733. public function getCommandId() { return 'SMEMBERS'; }
  1734. }
  1735. class Predis_Commands_SetRandomMember extends Predis_MultiBulkCommand {
  1736. public function getCommandId() { return 'SRANDMEMBER'; }
  1737. }
  1738. /* commands operating on sorted sets */
  1739. class Predis_Commands_ZSetAdd extends Predis_MultiBulkCommand {
  1740. public function getCommandId() { return 'ZADD'; }
  1741. public function parseResponse($data) { return (bool) $data; }
  1742. }
  1743. class Predis_Commands_ZSetIncrementBy extends Predis_MultiBulkCommand {
  1744. public function getCommandId() { return 'ZINCRBY'; }
  1745. }
  1746. class Predis_Commands_ZSetRemove extends Predis_MultiBulkCommand {
  1747. public function getCommandId() { return 'ZREM'; }
  1748. public function parseResponse($data) { return (bool) $data; }
  1749. }
  1750. class Predis_Commands_ZSetUnionStore extends Predis_MultiBulkCommand {
  1751. public function getCommandId() { return 'ZUNIONSTORE'; }
  1752. public function filterArguments(Array $arguments) {
  1753. $options = array();
  1754. $argc = count($arguments);
  1755. if ($argc > 1 && is_array($arguments[$argc - 1])) {
  1756. $options = $this->prepareOptions(array_pop($arguments));
  1757. }
  1758. $args = is_array($arguments[0]) ? $arguments[0] : $arguments;
  1759. return array_merge($args, $options);
  1760. }
  1761. private function prepareOptions($options) {
  1762. $opts = array_change_key_case($options, CASE_UPPER);
  1763. $finalizedOpts = array();
  1764. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  1765. $finalizedOpts[] = 'WEIGHTS';
  1766. $finalizedOpts[] = $opts['WEIGHTS'][0];
  1767. $finalizedOpts[] = $opts['WEIGHTS'][1];
  1768. }
  1769. if (isset($opts['AGGREGATE'])) {
  1770. $finalizedOpts[] = 'AGGREGATE';
  1771. $finalizedOpts[] = $opts['AGGREGATE'];
  1772. }
  1773. return $finalizedOpts;
  1774. }
  1775. }
  1776. class Predis_Commands_ZSetIntersectionStore extends Predis_Commands_ZSetUnionStore {
  1777. public function getCommandId() { return 'ZINTERSTORE'; }
  1778. }
  1779. class Predis_Commands_ZSetRange extends Predis_MultiBulkCommand {
  1780. public function getCommandId() { return 'ZRANGE'; }
  1781. public function parseResponse($data) {
  1782. $arguments = $this->getArguments();
  1783. if (count($arguments) === 4) {
  1784. if (strtolower($arguments[3]) === 'withscores') {
  1785. if ($data instanceof Iterator) {
  1786. return new Predis_Utilities_MultiBulkResponseKVIterator($data);
  1787. }
  1788. $result = array();
  1789. for ($i = 0; $i < count($data); $i++) {
  1790. $result[] = array($data[$i], $data[++$i]);
  1791. }
  1792. return $result;
  1793. }
  1794. }
  1795. return $data;
  1796. }
  1797. }
  1798. class Predis_Commands_ZSetReverseRange extends Predis_Commands_ZSetRange {
  1799. public function getCommandId() { return 'ZREVRANGE'; }
  1800. }
  1801. class Predis_Commands_ZSetRangeByScore extends Predis_Commands_ZSetRange {
  1802. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1803. }
  1804. class Predis_Commands_ZSetCount extends Predis_MultiBulkCommand {
  1805. public function getCommandId() { return 'ZCOUNT'; }
  1806. }
  1807. class Predis_Commands_ZSetCardinality extends Predis_MultiBulkCommand {
  1808. public function getCommandId() { return 'ZCARD'; }
  1809. }
  1810. class Predis_Commands_ZSetScore extends Predis_MultiBulkCommand {
  1811. public function getCommandId() { return 'ZSCORE'; }
  1812. }
  1813. class Predis_Commands_ZSetRemoveRangeByScore extends Predis_MultiBulkCommand {
  1814. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1815. }
  1816. class Predis_Commands_ZSetRank extends Predis_MultiBulkCommand {
  1817. public function getCommandId() { return 'ZRANK'; }
  1818. }
  1819. class Predis_Commands_ZSetReverseRank extends Predis_MultiBulkCommand {
  1820. public function getCommandId() { return 'ZREVRANK'; }
  1821. }
  1822. class Predis_Commands_ZSetRemoveRangeByRank extends Predis_MultiBulkCommand {
  1823. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1824. }
  1825. /* commands operating on hashes */
  1826. class Predis_Commands_HashSet extends Predis_MultiBulkCommand {
  1827. public function getCommandId() { return 'HSET'; }
  1828. public function parseResponse($data) { return (bool) $data; }
  1829. }
  1830. class Predis_Commands_HashSetPreserve extends Predis_MultiBulkCommand {
  1831. public function getCommandId() { return 'HSETNX'; }
  1832. public function parseResponse($data) { return (bool) $data; }
  1833. }
  1834. class Predis_Commands_HashSetMultiple extends Predis_MultiBulkCommand {
  1835. public function getCommandId() { return 'HMSET'; }
  1836. public function filterArguments(Array $arguments) {
  1837. if (count($arguments) === 2 && is_array($arguments[1])) {
  1838. $flattenedKVs = array($arguments[0]);
  1839. $args = &$arguments[1];
  1840. foreach ($args as $k => $v) {
  1841. $flattenedKVs[] = $k;
  1842. $flattenedKVs[] = $v;
  1843. }
  1844. return $flattenedKVs;
  1845. }
  1846. return $arguments;
  1847. }
  1848. }
  1849. class Predis_Commands_HashIncrementBy extends Predis_MultiBulkCommand {
  1850. public function getCommandId() { return 'HINCRBY'; }
  1851. }
  1852. class Predis_Commands_HashGet extends Predis_MultiBulkCommand {
  1853. public function getCommandId() { return 'HGET'; }
  1854. }
  1855. class Predis_Commands_HashGetMultiple extends Predis_MultiBulkCommand {
  1856. public function getCommandId() { return 'HMGET'; }
  1857. public function filterArguments(Array $arguments) {
  1858. if (count($arguments) === 2 && is_array($arguments[1])) {
  1859. $flattenedKVs = array($arguments[0]);
  1860. $args = &$arguments[1];
  1861. foreach ($args as $v) {
  1862. $flattenedKVs[] = $v;
  1863. }
  1864. return $flattenedKVs;
  1865. }
  1866. return $arguments;
  1867. }
  1868. }
  1869. class Predis_Commands_HashDelete extends Predis_MultiBulkCommand {
  1870. public function getCommandId() { return 'HDEL'; }
  1871. public function parseResponse($data) { return (bool) $data; }
  1872. }
  1873. class Predis_Commands_HashExists extends Predis_MultiBulkCommand {
  1874. public function getCommandId() { return 'HEXISTS'; }
  1875. public function parseResponse($data) { return (bool) $data; }
  1876. }
  1877. class Predis_Commands_HashLength extends Predis_MultiBulkCommand {
  1878. public function getCommandId() { return 'HLEN'; }
  1879. }
  1880. class Predis_Commands_HashKeys extends Predis_MultiBulkCommand {
  1881. public function getCommandId() { return 'HKEYS'; }
  1882. }
  1883. class Predis_Commands_HashValues extends Predis_MultiBulkCommand {
  1884. public function getCommandId() { return 'HVALS'; }
  1885. }
  1886. class Predis_Commands_HashGetAll extends Predis_MultiBulkCommand {
  1887. public function getCommandId() { return 'HGETALL'; }
  1888. public function parseResponse($data) {
  1889. if ($data instanceof Iterator) {
  1890. return new Predis_Utilities_MultiBulkResponseKVIterator($data);
  1891. }
  1892. $result = array();
  1893. for ($i = 0; $i < count($data); $i++) {
  1894. $result[$data[$i]] = $data[++$i];
  1895. }
  1896. return $result;
  1897. }
  1898. }
  1899. /* multiple databases handling commands */
  1900. class Predis_Commands_SelectDatabase extends Predis_MultiBulkCommand {
  1901. public function canBeHashed() { return false; }
  1902. public function getCommandId() { return 'SELECT'; }
  1903. }
  1904. class Predis_Commands_MoveKey extends Predis_MultiBulkCommand {
  1905. public function canBeHashed() { return false; }
  1906. public function getCommandId() { return 'MOVE'; }
  1907. public function parseResponse($data) { return (bool) $data; }
  1908. }
  1909. class Predis_Commands_FlushDatabase extends Predis_MultiBulkCommand {
  1910. public function canBeHashed() { return false; }
  1911. public function getCommandId() { return 'FLUSHDB'; }
  1912. }
  1913. class Predis_Commands_FlushAll extends Predis_MultiBulkCommand {
  1914. public function canBeHashed() { return false; }
  1915. public function getCommandId() { return 'FLUSHALL'; }
  1916. }
  1917. /* sorting */
  1918. class Predis_Commands_Sort extends Predis_MultiBulkCommand {
  1919. public function getCommandId() { return 'SORT'; }
  1920. public function filterArguments(Array $arguments) {
  1921. if (count($arguments) === 1) {
  1922. return $arguments;
  1923. }
  1924. // TODO: add more parameters checks
  1925. $query = array($arguments[0]);
  1926. $sortParams = $arguments[1];
  1927. if (isset($sortParams['by'])) {
  1928. $query[] = 'BY';
  1929. $query[] = $sortParams['by'];
  1930. }
  1931. if (isset($sortParams['get'])) {
  1932. $getargs = $sortParams['get'];
  1933. if (is_array($getargs)) {
  1934. foreach ($getargs as $getarg) {
  1935. $query[] = 'GET';
  1936. $query[] = $getarg;
  1937. }
  1938. }
  1939. else {
  1940. $query[] = 'GET';
  1941. $query[] = $getargs;
  1942. }
  1943. }
  1944. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1945. $query[] = 'LIMIT';
  1946. $query[] = $sortParams['limit'][0];
  1947. $query[] = $sortParams['limit'][1];
  1948. }
  1949. if (isset($sortParams['sort'])) {
  1950. $query[] = strtoupper($sortParams['sort']);
  1951. }
  1952. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1953. $query[] = 'ALPHA';
  1954. }
  1955. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1956. $query[] = 'STORE';
  1957. $query[] = $sortParams['store'];
  1958. }
  1959. return $query;
  1960. }
  1961. }
  1962. /* transactions */
  1963. class Predis_Commands_Multi extends Predis_MultiBulkCommand {
  1964. public function canBeHashed() { return false; }
  1965. public function getCommandId() { return 'MULTI'; }
  1966. }
  1967. class Predis_Commands_Exec extends Predis_MultiBulkCommand {
  1968. public function canBeHashed() { return false; }
  1969. public function getCommandId() { return 'EXEC'; }
  1970. }
  1971. class Predis_Commands_Discard extends Predis_MultiBulkCommand {
  1972. public function canBeHashed() { return false; }
  1973. public function getCommandId() { return 'DISCARD'; }
  1974. }
  1975. /* publish/subscribe */
  1976. class Predis_Commands_Subscribe extends Predis_MultiBulkCommand {
  1977. public function canBeHashed() { return false; }
  1978. public function getCommandId() { return 'SUBSCRIBE'; }
  1979. }
  1980. class Predis_Commands_Unsubscribe extends Predis_MultiBulkCommand {
  1981. public function canBeHashed() { return false; }
  1982. public function getCommandId() { return 'UNSUBSCRIBE'; }
  1983. }
  1984. class Predis_Commands_SubscribeByPattern extends Predis_MultiBulkCommand {
  1985. public function canBeHashed() { return false; }
  1986. public function getCommandId() { return 'PSUBSCRIBE'; }
  1987. }
  1988. class Predis_Commands_UnsubscribeByPattern extends Predis_MultiBulkCommand {
  1989. public function canBeHashed() { return false; }
  1990. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  1991. }
  1992. class Predis_Commands_Publish extends Predis_MultiBulkCommand {
  1993. public function canBeHashed() { return false; }
  1994. public function getCommandId() { return 'PUBLISH'; }
  1995. }
  1996. /* persistence control commands */
  1997. class Predis_Commands_Save extends Predis_MultiBulkCommand {
  1998. public function canBeHashed() { return false; }
  1999. public function getCommandId() { return 'SAVE'; }
  2000. }
  2001. class Predis_Commands_BackgroundSave extends Predis_MultiBulkCommand {
  2002. public function canBeHashed() { return false; }
  2003. public function getCommandId() { return 'BGSAVE'; }
  2004. public function parseResponse($data) {
  2005. if ($data == 'Background saving started') {
  2006. return true;
  2007. }
  2008. return $data;
  2009. }
  2010. }
  2011. class Predis_Commands_BackgroundRewriteAppendOnlyFile extends Predis_MultiBulkCommand {
  2012. public function canBeHashed() { return false; }
  2013. public function getCommandId() { return 'BGREWRITEAOF'; }
  2014. public function parseResponse($data) {
  2015. return $data == 'Background append only file rewriting started';
  2016. }
  2017. }
  2018. class Predis_Commands_LastSave extends Predis_MultiBulkCommand {
  2019. public function canBeHashed() { return false; }
  2020. public function getCommandId() { return 'LASTSAVE'; }
  2021. }
  2022. class Predis_Commands_Shutdown extends Predis_MultiBulkCommand {
  2023. public function canBeHashed() { return false; }
  2024. public function getCommandId() { return 'SHUTDOWN'; }
  2025. public function closesConnection() { return true; }
  2026. }
  2027. /* remote server control commands */
  2028. class Predis_Commands_Info extends Predis_MultiBulkCommand {
  2029. public function canBeHashed() { return false; }
  2030. public function getCommandId() { return 'INFO'; }
  2031. public function parseResponse($data) {
  2032. $info = array();
  2033. $infoLines = explode("\r\n", $data, -1);
  2034. foreach ($infoLines as $row) {
  2035. list($k, $v) = explode(':', $row);
  2036. if (!preg_match('/^db\d+$/', $k)) {
  2037. $info[$k] = $v;
  2038. }
  2039. else {
  2040. $db = array();
  2041. foreach (explode(',', $v) as $dbvar) {
  2042. list($dbvk, $dbvv) = explode('=', $dbvar);
  2043. $db[trim($dbvk)] = $dbvv;
  2044. }
  2045. $info[$k] = $db;
  2046. }
  2047. }
  2048. return $info;
  2049. }
  2050. }
  2051. class Predis_Commands_SlaveOf extends Predis_MultiBulkCommand {
  2052. public function canBeHashed() { return false; }
  2053. public function getCommandId() { return 'SLAVEOF'; }
  2054. public function filterArguments(Array $arguments) {
  2055. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2056. return array('NO', 'ONE');
  2057. }
  2058. return $arguments;
  2059. }
  2060. }
  2061. class Predis_Commands_Config extends Predis_MultiBulkCommand {
  2062. public function canBeHashed() { return false; }
  2063. public function getCommandId() { return 'CONFIG'; }
  2064. }
  2065. ?>