Predis.php 90 KB

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