Predis.php 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091
  1. <?php
  2. class PredisException extends Exception { }
  3. // Client-side errors
  4. class Predis_ClientException extends PredisException { }
  5. // Aborted multi/exec
  6. class Predis_AbortedMultiExec extends PredisException { }
  7. // Server-side errors
  8. class Predis_ServerException extends PredisException {
  9. public function toResponseError() {
  10. return new Predis_ResponseError($this->getMessage());
  11. }
  12. }
  13. // Communication errors
  14. class Predis_CommunicationException extends PredisException {
  15. private $_connection;
  16. public function __construct(Predis_Connection $connection, $message = null, $code = null) {
  17. $this->_connection = $connection;
  18. parent::__construct($message, $code);
  19. }
  20. public function getConnection() { return $this->_connection; }
  21. public function shouldResetConnection() { return true; }
  22. }
  23. // Unexpected responses
  24. class Predis_MalformedServerResponse extends Predis_CommunicationException { }
  25. /* ------------------------------------------------------------------------- */
  26. class Predis_Client {
  27. private $_options, $_connection, $_serverProfile, $_responseReader;
  28. public function __construct($parameters = null, $clientOptions = null) {
  29. $this->setupClient($clientOptions !== null ? $clientOptions : new Predis_ClientOptions());
  30. $this->setupConnection($parameters);
  31. }
  32. public static function create(/* arguments */) {
  33. $argv = func_get_args();
  34. $argc = func_num_args();
  35. $options = null;
  36. $lastArg = $argv[$argc-1];
  37. if ($argc > 0 && !is_string($lastArg) && ($lastArg instanceof Predis_ClientOptions ||
  38. is_subclass_of($lastArg, 'Predis_RedisServerProfile'))) {
  39. $options = array_pop($argv);
  40. $argc--;
  41. }
  42. if ($argc === 0) {
  43. throw new Predis_ClientException('Missing connection parameters');
  44. }
  45. return new Predis_Client($argc === 1 ? $argv[0] : $argv, $options);
  46. }
  47. private static function filterClientOptions($options) {
  48. if ($options instanceof Predis_ClientOptions) {
  49. return $options;
  50. }
  51. if (is_array($options)) {
  52. return new Predis_ClientOptions($options);
  53. }
  54. if ($options instanceof Predis_RedisServerProfile) {
  55. return new Predis_ClientOptions(array(
  56. 'profile' => $options
  57. ));
  58. }
  59. if (is_string($options)) {
  60. return new Predis_ClientOptions(array(
  61. 'profile' => Predis_RedisServerProfile::get($options)
  62. ));
  63. }
  64. throw new InvalidArgumentException("Invalid type for client options");
  65. }
  66. private function setupClient($options) {
  67. $this->_responseReader = new Predis_ResponseReader();
  68. $this->_options = self::filterClientOptions($options);
  69. $this->setProfile($this->_options->profile);
  70. if ($this->_options->iterable_multibulk === true) {
  71. $this->_responseReader->setHandler(
  72. Predis_Protocol::PREFIX_MULTI_BULK,
  73. new Predis_ResponseMultiBulkStreamHandler()
  74. );
  75. }
  76. if ($this->_options->throw_on_error === false) {
  77. $this->_responseReader->setHandler(
  78. Predis_Protocol::PREFIX_ERROR,
  79. new Predis_ResponseErrorSilentHandler()
  80. );
  81. }
  82. }
  83. private function setupConnection($parameters) {
  84. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  85. throw new Predis_ClientException('Invalid parameters type (array or string expected)');
  86. }
  87. if (is_array($parameters) && isset($parameters[0])) {
  88. $cluster = new Predis_ConnectionCluster($this->_options->key_distribution);
  89. foreach ($parameters as $shardParams) {
  90. $cluster->add($this->createConnection($shardParams));
  91. }
  92. $this->setConnection($cluster);
  93. }
  94. else {
  95. $this->setConnection($this->createConnection($parameters));
  96. }
  97. }
  98. private function createConnection($parameters) {
  99. $params = $parameters instanceof Predis_ConnectionParameters
  100. ? $parameters
  101. : new Predis_ConnectionParameters($parameters);
  102. $connection = new Predis_Connection($params, $this->_responseReader);
  103. if ($params->password !== null) {
  104. $connection->pushInitCommand($this->createCommand(
  105. 'auth', array($params->password)
  106. ));
  107. }
  108. if ($params->database !== null) {
  109. $connection->pushInitCommand($this->createCommand(
  110. 'select', array($params->database)
  111. ));
  112. }
  113. return $connection;
  114. }
  115. private function setConnection(Predis_IConnection $connection) {
  116. $this->_connection = $connection;
  117. }
  118. public function setProfile($serverProfile) {
  119. if (!($serverProfile instanceof Predis_RedisServerProfile || is_string($serverProfile))) {
  120. throw new InvalidArgumentException(
  121. "Invalid type for server profile, Predis_RedisServerProfile or string expected"
  122. );
  123. }
  124. $this->_serverProfile = (is_string($serverProfile)
  125. ? Predis_RedisServerProfile::get($serverProfile)
  126. : $serverProfile
  127. );
  128. }
  129. public function getProfile() {
  130. return $this->_serverProfile;
  131. }
  132. public function getResponseReader() {
  133. return $this->_responseReader;
  134. }
  135. public function getClientFor($connectionAlias) {
  136. if (!Predis_Shared_Utils::isCluster($this->_connection)) {
  137. throw new Predis_ClientException(
  138. 'This method is supported only when the client is connected to a cluster of connections'
  139. );
  140. }
  141. $connection = $this->_connection->getConnectionById($connectionAlias);
  142. if ($connection === null) {
  143. throw new InvalidArgumentException(
  144. "Invalid connection alias: '$connectionAlias'"
  145. );
  146. }
  147. $newClient = new Predis_Client();
  148. $newClient->setupClient($this->_options);
  149. $newClient->setConnection($connection);
  150. return $newClient;
  151. }
  152. public function connect() {
  153. $this->_connection->connect();
  154. }
  155. public function disconnect() {
  156. $this->_connection->disconnect();
  157. }
  158. public function isConnected() {
  159. return $this->_connection->isConnected();
  160. }
  161. public function getConnection($id = null) {
  162. if (!isset($id)) {
  163. return $this->_connection;
  164. }
  165. else {
  166. return Predis_Shared_Utils::isCluster($this->_connection)
  167. ? $this->_connection->getConnectionById($id)
  168. : $this->_connection;
  169. }
  170. }
  171. public function __call($method, $arguments) {
  172. $command = $this->_serverProfile->createCommand($method, $arguments);
  173. return $this->_connection->executeCommand($command);
  174. }
  175. public function createCommand($method, $arguments = array()) {
  176. return $this->_serverProfile->createCommand($method, $arguments);
  177. }
  178. public function executeCommand(Predis_Command $command) {
  179. return $this->_connection->executeCommand($command);
  180. }
  181. public function executeCommandOnShards(Predis_Command $command) {
  182. $replies = array();
  183. if (Predis_Shared_Utils::isCluster($this->_connection)) {
  184. foreach($this->_connection as $connection) {
  185. $replies[] = $connection->executeCommand($command);
  186. }
  187. }
  188. else {
  189. $replies[] = $this->_connection->executeCommand($command);
  190. }
  191. return $replies;
  192. }
  193. public function rawCommand($rawCommandData, $closesConnection = false) {
  194. if (Predis_Shared_Utils::isCluster($this->_connection)) {
  195. throw new Predis_ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  196. }
  197. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  198. }
  199. private function sharedInitializer($argv, $initializer) {
  200. $argc = count($argv);
  201. if ($argc === 0) {
  202. return $this->$initializer();
  203. }
  204. else if ($argc === 1) {
  205. list($arg0) = $argv;
  206. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  207. }
  208. else if ($argc === 2) {
  209. list($arg0, $arg1) = $argv;
  210. return $this->$initializer($arg0, $arg1);
  211. }
  212. return $this->$initializer($this, $arguments);
  213. }
  214. public function pipeline(/* arguments */) {
  215. $args = func_get_args();
  216. return $this->sharedInitializer($args, 'initPipeline');
  217. }
  218. public function pipelineSafe($pipelineBlock = null) {
  219. return $this->initPipeline(array('safe' => true), $pipelineBlock);
  220. }
  221. private function initPipeline(Array $options = null, $pipelineBlock = null) {
  222. $pipeline = null;
  223. if (isset($options)) {
  224. if (isset($options['safe']) && $options['safe'] == true) {
  225. $connection = $this->getConnection();
  226. $pipeline = new Predis_CommandPipeline($this, $connection instanceof Predis_Connection
  227. ? new Predis_Pipeline_SafeExecutor($connection)
  228. : new Predis_Pipeline_SafeClusterExecutor($connection)
  229. );
  230. }
  231. else {
  232. $pipeline = new Predis_CommandPipeline($this);
  233. }
  234. }
  235. else {
  236. $pipeline = new Predis_CommandPipeline($this);
  237. }
  238. return $this->pipelineExecute($pipeline, $pipelineBlock);
  239. }
  240. private function pipelineExecute(Predis_CommandPipeline $pipeline, $block) {
  241. return $block !== null ? $pipeline->execute($block) : $pipeline;
  242. }
  243. public function multiExec(/* arguments */) {
  244. $args = func_get_args();
  245. return $this->sharedInitializer($args, 'initMultiExec');
  246. }
  247. private function initMultiExec(Array $options = null, $transBlock = null) {
  248. $multi = isset($options) ? new Predis_MultiExecBlock($this, $options) : new Predis_MultiExecBlock($this);
  249. return $transBlock !== null ? $multi->execute($transBlock) : $multi;
  250. }
  251. public function pubSubContext(Array $options = null) {
  252. return new Predis_PubSubContext($this, $options);
  253. }
  254. }
  255. /* ------------------------------------------------------------------------- */
  256. interface Predis_IClientOptionsHandler {
  257. public function validate($option, $value);
  258. public function getDefault();
  259. }
  260. class Predis_ClientOptionsProfile implements Predis_IClientOptionsHandler {
  261. public function validate($option, $value) {
  262. if ($value instanceof Predis_RedisServerProfile) {
  263. return $value;
  264. }
  265. if (is_string($value)) {
  266. return Predis_RedisServerProfile::get($value);
  267. }
  268. throw new InvalidArgumentException("Invalid value for option $option");
  269. }
  270. public function getDefault() {
  271. return Predis_RedisServerProfile::getDefault();
  272. }
  273. }
  274. class Predis_ClientOptionsKeyDistribution implements Predis_IClientOptionsHandler {
  275. public function validate($option, $value) {
  276. if ($value instanceof Predis_Distribution_IDistributionStrategy) {
  277. return $value;
  278. }
  279. if (is_string($value)) {
  280. $valueReflection = new ReflectionClass($value);
  281. if ($valueReflection->isSubclassOf('Predis_Distribution_IDistributionStrategy')) {
  282. return new $value;
  283. }
  284. }
  285. throw new InvalidArgumentException("Invalid value for option $option");
  286. }
  287. public function getDefault() {
  288. return new Predis_Distribution_HashRing();
  289. }
  290. }
  291. class Predis_ClientOptionsIterableMultiBulk implements Predis_IClientOptionsHandler {
  292. public function validate($option, $value) {
  293. return (bool) $value;
  294. }
  295. public function getDefault() {
  296. return false;
  297. }
  298. }
  299. class Predis_ClientOptionsThrowOnError implements Predis_IClientOptionsHandler {
  300. public function validate($option, $value) {
  301. return (bool) $value;
  302. }
  303. public function getDefault() {
  304. return true;
  305. }
  306. }
  307. class Predis_ClientOptions {
  308. private static $_optionsHandlers;
  309. private $_options;
  310. public function __construct($options = null) {
  311. self::initializeOptionsHandlers();
  312. $this->initializeOptions($options !== null ? $options : array());
  313. }
  314. private static function initializeOptionsHandlers() {
  315. if (!isset(self::$_optionsHandlers)) {
  316. self::$_optionsHandlers = self::getOptionsHandlers();
  317. }
  318. }
  319. private static function getOptionsHandlers() {
  320. return array(
  321. 'profile' => new Predis_ClientOptionsProfile(),
  322. 'key_distribution' => new Predis_ClientOptionsKeyDistribution(),
  323. 'iterable_multibulk' => new Predis_ClientOptionsIterableMultiBulk(),
  324. 'throw_on_error' => new Predis_ClientOptionsThrowOnError(),
  325. );
  326. }
  327. private function initializeOptions($options) {
  328. foreach ($options as $option => $value) {
  329. if (isset(self::$_optionsHandlers[$option])) {
  330. $handler = self::$_optionsHandlers[$option];
  331. $this->_options[$option] = $handler->validate($option, $value);
  332. }
  333. }
  334. }
  335. public function __get($option) {
  336. if (!isset($this->_options[$option])) {
  337. $defaultValue = self::$_optionsHandlers[$option]->getDefault();
  338. $this->_options[$option] = $defaultValue;
  339. }
  340. return $this->_options[$option];
  341. }
  342. public function __isset($option) {
  343. return isset(self::$_optionsHandlers[$option]);
  344. }
  345. }
  346. /* ------------------------------------------------------------------------- */
  347. class Predis_Protocol {
  348. const NEWLINE = "\r\n";
  349. const OK = 'OK';
  350. const ERROR = 'ERR';
  351. const QUEUED = 'QUEUED';
  352. const NULL = 'nil';
  353. const PREFIX_STATUS = '+';
  354. const PREFIX_ERROR = '-';
  355. const PREFIX_INTEGER = ':';
  356. const PREFIX_BULK = '$';
  357. const PREFIX_MULTI_BULK = '*';
  358. }
  359. abstract class Predis_Command {
  360. private $_hash;
  361. private $_arguments = array();
  362. public abstract function getCommandId();
  363. public abstract function serializeRequest($command, $arguments);
  364. public function canBeHashed() {
  365. return true;
  366. }
  367. public function getHash(Predis_Distribution_IDistributionStrategy $distributor) {
  368. if (isset($this->_hash)) {
  369. return $this->_hash;
  370. }
  371. if (isset($this->_arguments[0])) {
  372. // TODO: should we throw an exception if the command does
  373. // not support sharding?
  374. $key = $this->_arguments[0];
  375. $start = strpos($key, '{');
  376. if ($start !== false) {
  377. $end = strpos($key, '}', $start);
  378. if ($end !== false) {
  379. $key = substr($key, ++$start, $end - $start);
  380. }
  381. }
  382. $this->_hash = $distributor->generateKey($key);
  383. return $this->_hash;
  384. }
  385. return null;
  386. }
  387. public function closesConnection() {
  388. return false;
  389. }
  390. protected function filterArguments(Array $arguments) {
  391. return $arguments;
  392. }
  393. public function setArguments(/* arguments */) {
  394. $this->_arguments = $this->filterArguments(func_get_args());
  395. unset($this->_hash);
  396. }
  397. public function setArgumentsArray(Array $arguments) {
  398. $this->_arguments = $this->filterArguments($arguments);
  399. unset($this->_hash);
  400. }
  401. public function getArguments() {
  402. return $this->_arguments;
  403. }
  404. public function getArgument($index = 0) {
  405. if (isset($this->_arguments[$index]) === true) {
  406. return $this->_arguments[$index];
  407. }
  408. }
  409. public function parseResponse($data) {
  410. return $data;
  411. }
  412. public final function invoke() {
  413. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  414. }
  415. }
  416. abstract class Predis_InlineCommand extends Predis_Command {
  417. public function serializeRequest($command, $arguments) {
  418. if (isset($arguments[0]) && is_array($arguments[0])) {
  419. $arguments[0] = implode($arguments[0], ' ');
  420. }
  421. return $command . (count($arguments) > 0
  422. ? ' ' . implode($arguments, ' ') . "\r\n" : "\r\n"
  423. );
  424. }
  425. }
  426. abstract class Predis_BulkCommand extends Predis_Command {
  427. public function serializeRequest($command, $arguments) {
  428. $data = array_pop($arguments);
  429. if (is_array($data)) {
  430. $data = implode($data, ' ');
  431. }
  432. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  433. "\r\n" . $data . "\r\n";
  434. }
  435. }
  436. abstract class Predis_MultiBulkCommand extends Predis_Command {
  437. public function serializeRequest($command, $arguments) {
  438. $cmd_args = null;
  439. $argsc = count($arguments);
  440. if ($argsc === 1 && is_array($arguments[0])) {
  441. $cmd_args = $arguments[0];
  442. $argsc = count($cmd_args);
  443. }
  444. else {
  445. $cmd_args = $arguments;
  446. }
  447. $cmdlen = strlen($command);
  448. $reqlen = $argsc + 1;
  449. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$command}\r\n";
  450. for ($i = 0; $i < $reqlen - 1; $i++) {
  451. $argument = $cmd_args[$i];
  452. $arglen = strlen($argument);
  453. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  454. }
  455. return $buffer;
  456. }
  457. }
  458. /* ------------------------------------------------------------------------- */
  459. interface Predis_IResponseHandler {
  460. function handle(Predis_Connection $connection, $payload);
  461. }
  462. class Predis_ResponseStatusHandler implements Predis_IResponseHandler {
  463. public function handle(Predis_Connection $connection, $status) {
  464. if ($status === "OK") {
  465. return true;
  466. }
  467. if ($status === "QUEUED") {
  468. return new Predis_ResponseQueued();
  469. }
  470. return $status;
  471. }
  472. }
  473. class Predis_ResponseErrorHandler implements Predis_IResponseHandler {
  474. public function handle(Predis_Connection $connection, $errorMessage) {
  475. throw new Predis_ServerException(substr($errorMessage, 4));
  476. }
  477. }
  478. class Predis_ResponseErrorSilentHandler implements Predis_IResponseHandler {
  479. public function handle(Predis_Connection $connection, $errorMessage) {
  480. return new Predis_ResponseError(substr($errorMessage, 4));
  481. }
  482. }
  483. class Predis_ResponseBulkHandler implements Predis_IResponseHandler {
  484. public function handle(Predis_Connection $connection, $lengthString) {
  485. $length = (int) $lengthString;
  486. if ($length != $lengthString) {
  487. Predis_Shared_Utils::onCommunicationException(new Predis_MalformedServerResponse(
  488. $connection, "Cannot parse '$length' as data length"
  489. ));
  490. }
  491. if ($length >= 0) {
  492. return substr($connection->readBytes($length + 2), 0, -2);
  493. }
  494. if ($length == -1) {
  495. return null;
  496. }
  497. }
  498. }
  499. class Predis_ResponseMultiBulkHandler implements Predis_IResponseHandler {
  500. public function handle(Predis_Connection $connection, $lengthString) {
  501. $listLength = (int) $lengthString;
  502. if ($listLength != $lengthString) {
  503. Predis_Shared_Utils::onCommunicationException(new Predis_MalformedServerResponse(
  504. $connection, "Cannot parse '$lengthString' as data length"
  505. ));
  506. }
  507. if ($listLength === -1) {
  508. return null;
  509. }
  510. $list = array();
  511. if ($listLength > 0) {
  512. $handlers = array();
  513. $reader = $connection->getResponseReader();
  514. for ($i = 0; $i < $listLength; $i++) {
  515. $header = $connection->readLine();
  516. $prefix = $header[0];
  517. if (isset($handlers[$prefix])) {
  518. $handler = $handlers[$prefix];
  519. }
  520. else {
  521. $handler = $reader->getHandler($prefix);
  522. $handlers[$prefix] = $handler;
  523. }
  524. $list[$i] = $handler->handle($connection, substr($header, 1));
  525. }
  526. }
  527. return $list;
  528. }
  529. }
  530. class Predis_ResponseMultiBulkStreamHandler implements Predis_IResponseHandler {
  531. public function handle(Predis_Connection $connection, $lengthString) {
  532. $listLength = (int) $lengthString;
  533. if ($listLength != $lengthString) {
  534. Predis_Shared_Utils::onCommunicationException(new Predis_MalformedServerResponse(
  535. $connection, "Cannot parse '$lengthString' as data length"
  536. ));
  537. }
  538. return new Predis_Shared_MultiBulkResponseIterator($connection, $lengthString);
  539. }
  540. }
  541. class Predis_ResponseIntegerHandler implements Predis_IResponseHandler {
  542. public function handle(Predis_Connection $connection, $number) {
  543. if (is_numeric($number)) {
  544. return (int) $number;
  545. }
  546. else {
  547. if ($number !== 'nil') {
  548. Predis_Shared_Utils::onCommunicationException(new Predis_MalformedServerResponse(
  549. $connection, "Cannot parse '$number' as numeric response"
  550. ));
  551. }
  552. return null;
  553. }
  554. }
  555. }
  556. class Predis_ResponseReader {
  557. private $_prefixHandlers;
  558. public function __construct() {
  559. $this->initializePrefixHandlers();
  560. }
  561. private function initializePrefixHandlers() {
  562. $this->_prefixHandlers = array(
  563. Predis_Protocol::PREFIX_STATUS => new Predis_ResponseStatusHandler(),
  564. Predis_Protocol::PREFIX_ERROR => new Predis_ResponseErrorHandler(),
  565. Predis_Protocol::PREFIX_INTEGER => new Predis_ResponseIntegerHandler(),
  566. Predis_Protocol::PREFIX_BULK => new Predis_ResponseBulkHandler(),
  567. Predis_Protocol::PREFIX_MULTI_BULK => new Predis_ResponseMultiBulkHandler(),
  568. );
  569. }
  570. public function setHandler($prefix, Predis_IResponseHandler $handler) {
  571. $this->_prefixHandlers[$prefix] = $handler;
  572. }
  573. public function getHandler($prefix) {
  574. if (isset($this->_prefixHandlers[$prefix])) {
  575. return $this->_prefixHandlers[$prefix];
  576. }
  577. }
  578. public function read(Predis_Connection $connection) {
  579. $header = $connection->readLine();
  580. if ($header === '') {
  581. $this->throwMalformedResponse($connection, 'Unexpected empty header');
  582. }
  583. $prefix = $header[0];
  584. if (!isset($this->_prefixHandlers[$prefix])) {
  585. $this->throwMalformedResponse($connection, "Unknown prefix '$prefix'");
  586. }
  587. $handler = $this->_prefixHandlers[$prefix];
  588. return $handler->handle($connection, substr($header, 1));
  589. }
  590. private function throwMalformedResponse(Predis_Connection $connection, $message) {
  591. Predis_Shared_Utils::onCommunicationException(new Predis_MalformedServerResponse(
  592. $connection, $message
  593. ));
  594. }
  595. }
  596. class Predis_ResponseError {
  597. public $skipParse = true;
  598. private $_message;
  599. public function __construct($message) {
  600. $this->_message = $message;
  601. }
  602. public function __get($property) {
  603. if ($property === 'error') {
  604. return true;
  605. }
  606. if ($property === 'message') {
  607. return $this->_message;
  608. }
  609. }
  610. public function __isset($property) {
  611. return $property === 'error';
  612. }
  613. public function __toString() {
  614. return $this->_message;
  615. }
  616. }
  617. class Predis_ResponseQueued {
  618. public $skipParse = true;
  619. public function __toString() {
  620. return Predis_Protocol::QUEUED;
  621. }
  622. public function __get($property) {
  623. if ($property === 'queued') {
  624. return true;
  625. }
  626. }
  627. public function __isset($property) {
  628. return $property === 'queued';
  629. }
  630. }
  631. /* ------------------------------------------------------------------------- */
  632. class Predis_CommandPipeline {
  633. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running, $_executor;
  634. public function __construct(Predis_Client $redisClient, Predis_Pipeline_IPipelineExecutor $executor = null) {
  635. $this->_redisClient = $redisClient;
  636. $this->_executor = $executor !== null ? $executor : new Predis_Pipeline_StandardExecutor();
  637. $this->_pipelineBuffer = array();
  638. $this->_returnValues = array();
  639. }
  640. public function __call($method, $arguments) {
  641. $command = $this->_redisClient->createCommand($method, $arguments);
  642. $this->recordCommand($command);
  643. return $this;
  644. }
  645. private function recordCommand(Predis_Command $command) {
  646. $this->_pipelineBuffer[] = $command;
  647. }
  648. private function getRecordedCommands() {
  649. return $this->_pipelineBuffer;
  650. }
  651. public function flushPipeline() {
  652. if (count($this->_pipelineBuffer) > 0) {
  653. $connection = $this->_redisClient->getConnection();
  654. $this->_returnValues = array_merge(
  655. $this->_returnValues,
  656. $this->_executor->execute($connection, $this->_pipelineBuffer)
  657. );
  658. $this->_pipelineBuffer = array();
  659. }
  660. return $this;
  661. }
  662. private function setRunning($bool) {
  663. if ($bool == true && $this->_running == true) {
  664. throw new Predis_ClientException("This pipeline is already opened");
  665. }
  666. $this->_running = $bool;
  667. }
  668. public function execute($block = null) {
  669. if ($block && !is_callable($block)) {
  670. throw new InvalidArgumentException('Argument passed must be a callable object');
  671. }
  672. // TODO: do not reuse previously executed pipelines
  673. $this->setRunning(true);
  674. $pipelineBlockException = null;
  675. try {
  676. if ($block !== null) {
  677. $block($this);
  678. }
  679. $this->flushPipeline();
  680. }
  681. catch (Exception $exception) {
  682. $pipelineBlockException = $exception;
  683. }
  684. $this->setRunning(false);
  685. if ($pipelineBlockException !== null) {
  686. throw $pipelineBlockException;
  687. }
  688. return $this->_returnValues;
  689. }
  690. }
  691. class Predis_MultiExecBlock {
  692. private $_initialized, $_discarded, $_insideBlock, $_checkAndSet;
  693. private $_redisClient, $_options, $_commands;
  694. private $_supportsWatch;
  695. public function __construct(Predis_Client $redisClient, Array $options = null) {
  696. $this->checkCapabilities($redisClient);
  697. $this->_options = isset($options) ? $options : array();
  698. $this->_redisClient = $redisClient;
  699. $this->reset();
  700. }
  701. private function checkCapabilities(Predis_Client $redisClient) {
  702. if (Predis_Shared_Utils::isCluster($redisClient->getConnection())) {
  703. throw new Predis_ClientException(
  704. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  705. );
  706. }
  707. $profile = $redisClient->getProfile();
  708. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  709. throw new Predis_ClientException(
  710. 'The current profile does not support MULTI, EXEC and DISCARD commands'
  711. );
  712. }
  713. $this->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  714. }
  715. private function isWatchSupported() {
  716. if ($this->_supportsWatch === false) {
  717. throw new Predis_ClientException(
  718. 'The current profile does not support WATCH and UNWATCH commands'
  719. );
  720. }
  721. }
  722. private function reset() {
  723. $this->_initialized = false;
  724. $this->_discarded = false;
  725. $this->_checkAndSet = false;
  726. $this->_insideBlock = false;
  727. $this->_commands = array();
  728. }
  729. private function initialize() {
  730. if ($this->_initialized === true) {
  731. return;
  732. }
  733. $options = &$this->_options;
  734. $this->_checkAndSet = isset($options['cas']) && $options['cas'];
  735. if (isset($options['watch'])) {
  736. $this->watch($options['watch']);
  737. }
  738. if (!$this->_checkAndSet || ($this->_discarded && $this->_checkAndSet)) {
  739. $this->_redisClient->multi();
  740. if ($this->_discarded) {
  741. $this->_checkAndSet = false;
  742. }
  743. }
  744. $this->_initialized = true;
  745. $this->_discarded = false;
  746. }
  747. public function __call($method, $arguments) {
  748. $this->initialize();
  749. $client = $this->_redisClient;
  750. if ($this->_checkAndSet) {
  751. return call_user_func_array(array($client, $method), $arguments);
  752. }
  753. $command = $client->createCommand($method, $arguments);
  754. $response = $client->executeCommand($command);
  755. if (!$response instanceof Predis_ResponseQueued) {
  756. $this->malformedServerResponse(
  757. 'The server did not respond with a QUEUED status reply'
  758. );
  759. }
  760. $this->_commands[] = $command;
  761. return $this;
  762. }
  763. public function watch($keys) {
  764. $this->isWatchSupported();
  765. if ($this->_initialized && !$this->_checkAndSet) {
  766. throw new Predis_ClientException('WATCH inside MULTI is not allowed');
  767. }
  768. return $this->_redisClient->watch($keys);
  769. }
  770. public function multi() {
  771. if ($this->_initialized && $this->_checkAndSet) {
  772. $this->_checkAndSet = false;
  773. $this->_redisClient->multi();
  774. return $this;
  775. }
  776. $this->initialize();
  777. return $this;
  778. }
  779. public function unwatch() {
  780. $this->isWatchSupported();
  781. $this->_redisClient->unwatch();
  782. return $this;
  783. }
  784. public function discard() {
  785. $this->_redisClient->discard();
  786. $this->reset();
  787. $this->_discarded = true;
  788. return $this;
  789. }
  790. public function exec() {
  791. return $this->execute();
  792. }
  793. private function checkBeforeExecution($block) {
  794. if ($this->_insideBlock === true) {
  795. throw new Predis_ClientException(
  796. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  797. );
  798. }
  799. if ($block) {
  800. if (!is_callable($block)) {
  801. throw new InvalidArgumentException(
  802. 'Argument passed must be a callable object'
  803. );
  804. }
  805. if (count($this->_commands) > 0) {
  806. throw new Predis_ClientException(
  807. 'Cannot execute a transaction block after using fluent interface'
  808. );
  809. }
  810. }
  811. if (isset($this->_options['retry']) && !isset($block)) {
  812. $this->discard();
  813. throw new InvalidArgumentException(
  814. 'Automatic retries can be used only when a transaction block is provided'
  815. );
  816. }
  817. }
  818. public function execute($block = null) {
  819. $this->checkBeforeExecution($block);
  820. $reply = null;
  821. $returnValues = array();
  822. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  823. do {
  824. $blockException = null;
  825. if ($block !== null) {
  826. $this->_insideBlock = true;
  827. try {
  828. $block($this);
  829. }
  830. catch (Predis_CommunicationException $exception) {
  831. $blockException = $exception;
  832. }
  833. catch (Predis_ServerException $exception) {
  834. $blockException = $exception;
  835. }
  836. catch (Exception $exception) {
  837. $blockException = $exception;
  838. if ($this->_initialized === true) {
  839. $this->discard();
  840. }
  841. }
  842. $this->_insideBlock = false;
  843. if ($blockException !== null) {
  844. throw $blockException;
  845. }
  846. }
  847. if ($this->_initialized === false || count($this->_commands) == 0) {
  848. return;
  849. }
  850. $reply = $this->_redisClient->exec();
  851. if ($reply === null) {
  852. if ($attemptsLeft === 0) {
  853. throw new Predis_AbortedMultiExec(
  854. 'The current transaction has been aborted by the server'
  855. );
  856. }
  857. $this->reset();
  858. if (isset($this->_options['on_retry']) && is_callable($this->_options['on_retry'])) {
  859. call_user_func($this->_options['on_retry'], $this, $attemptsLeft);
  860. }
  861. continue;
  862. }
  863. break;
  864. } while ($attemptsLeft-- > 0);
  865. $execReply = $reply instanceof Iterator ? iterator_to_array($reply) : $reply;
  866. $sizeofReplies = count($execReply);
  867. $commands = &$this->_commands;
  868. if ($sizeofReplies !== count($commands)) {
  869. $this->malformedServerResponse(
  870. 'Unexpected number of responses for a MultiExecBlock'
  871. );
  872. }
  873. for ($i = 0; $i < $sizeofReplies; $i++) {
  874. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof Iterator
  875. ? iterator_to_array($execReply[$i])
  876. : $execReply[$i]
  877. );
  878. unset($commands[$i]);
  879. }
  880. return $returnValues;
  881. }
  882. private function malformedServerResponse($message) {
  883. // Since a MULTI/EXEC block cannot be initialized over a clustered
  884. // connection, we can safely assume that Predis_Client::getConnection()
  885. // will always return an instance of Predis_Connection.
  886. Predis_Shared_Utils::onCommunicationException(
  887. new Predis_MalformedServerResponse(
  888. $this->_redisClient->getConnection(), $message
  889. )
  890. );
  891. }
  892. }
  893. class Predis_PubSubContext implements Iterator {
  894. const SUBSCRIBE = 'subscribe';
  895. const UNSUBSCRIBE = 'unsubscribe';
  896. const PSUBSCRIBE = 'psubscribe';
  897. const PUNSUBSCRIBE = 'punsubscribe';
  898. const MESSAGE = 'message';
  899. const PMESSAGE = 'pmessage';
  900. const STATUS_VALID = 0x0001;
  901. const STATUS_SUBSCRIBED = 0x0010;
  902. const STATUS_PSUBSCRIBED = 0x0100;
  903. private $_redisClient, $_position, $_options;
  904. public function __construct(Predis_Client $redisClient, Array $options = null) {
  905. $this->checkCapabilities($redisClient);
  906. $this->_options = isset($options) ? $options : array();
  907. $this->_redisClient = $redisClient;
  908. $this->_statusFlags = self::STATUS_VALID;
  909. $this->genericSubscribeInit('subscribe');
  910. $this->genericSubscribeInit('psubscribe');
  911. }
  912. public function __destruct() {
  913. if ($this->valid()) {
  914. $this->closeContext();
  915. }
  916. }
  917. private function checkCapabilities(Predis_Client $redisClient) {
  918. if (Predis_Shared_Utils::isCluster($redisClient->getConnection())) {
  919. throw new Predis_ClientException(
  920. 'Cannot initialize a PUB/SUB context over a cluster of connections'
  921. );
  922. }
  923. $profile = $redisClient->getProfile();
  924. $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
  925. if ($profile->supportsCommands($commands) === false) {
  926. throw new Predis_ClientException(
  927. 'The current profile does not support PUB/SUB related commands'
  928. );
  929. }
  930. }
  931. private function genericSubscribeInit($subscribeAction) {
  932. if (isset($this->_options[$subscribeAction])) {
  933. if (is_array($this->_options[$subscribeAction])) {
  934. foreach ($this->_options[$subscribeAction] as $subscription) {
  935. $this->$subscribeAction($subscription);
  936. }
  937. }
  938. else {
  939. $this->$subscribeAction($this->_options[$subscribeAction]);
  940. }
  941. }
  942. }
  943. private function isFlagSet($value) {
  944. return ($this->_statusFlags & $value) === $value;
  945. }
  946. public function subscribe(/* arguments */) {
  947. $args = func_get_args();
  948. $this->writeCommand(self::SUBSCRIBE, $args);
  949. $this->_statusFlags |= self::STATUS_SUBSCRIBED;
  950. }
  951. public function unsubscribe(/* arguments */) {
  952. $args = func_get_args();
  953. $this->writeCommand(self::UNSUBSCRIBE, $args);
  954. }
  955. public function psubscribe(/* arguments */) {
  956. $args = func_get_args();
  957. $this->writeCommand(self::PSUBSCRIBE, $args);
  958. $this->_statusFlags |= self::STATUS_PSUBSCRIBED;
  959. }
  960. public function punsubscribe(/* arguments */) {
  961. $args = func_get_args();
  962. $this->writeCommand(self::PUNSUBSCRIBE, $args);
  963. }
  964. public function closeContext() {
  965. if ($this->valid()) {
  966. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  967. $this->unsubscribe();
  968. }
  969. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  970. $this->punsubscribe();
  971. }
  972. }
  973. }
  974. private function writeCommand($method, $arguments) {
  975. if (count($arguments) === 1 && is_array($arguments[0])) {
  976. $arguments = $arguments[0];
  977. }
  978. $command = $this->_redisClient->createCommand($method, $arguments);
  979. $this->_redisClient->getConnection()->writeCommand($command);
  980. }
  981. public function rewind() {
  982. // NOOP
  983. }
  984. public function current() {
  985. return $this->getValue();
  986. }
  987. public function key() {
  988. return $this->_position;
  989. }
  990. public function next() {
  991. if ($this->isFlagSet(self::STATUS_VALID)) {
  992. $this->_position++;
  993. }
  994. return $this->_position;
  995. }
  996. public function valid() {
  997. $subscriptions = self::STATUS_SUBSCRIBED + self::STATUS_PSUBSCRIBED;
  998. return $this->isFlagSet(self::STATUS_VALID)
  999. && ($this->_statusFlags & $subscriptions) > 0;
  1000. }
  1001. private function invalidate() {
  1002. $this->_statusFlags = 0x0000;
  1003. }
  1004. private function getValue() {
  1005. $reader = $this->_redisClient->getResponseReader();
  1006. $connection = $this->_redisClient->getConnection();
  1007. $response = $reader->read($connection);
  1008. switch ($response[0]) {
  1009. case self::SUBSCRIBE:
  1010. case self::UNSUBSCRIBE:
  1011. case self::PSUBSCRIBE:
  1012. case self::PUNSUBSCRIBE:
  1013. if ($response[2] === 0) {
  1014. $this->invalidate();
  1015. }
  1016. case self::MESSAGE:
  1017. return (object) array(
  1018. 'kind' => $response[0],
  1019. 'channel' => $response[1],
  1020. 'payload' => $response[2],
  1021. );
  1022. case self::PMESSAGE:
  1023. return (object) array(
  1024. 'kind' => $response[0],
  1025. 'pattern' => $response[1],
  1026. 'channel' => $response[2],
  1027. 'payload' => $response[3],
  1028. );
  1029. default:
  1030. throw new Predis_ClientException(
  1031. "Received an unknown message type {$response[0]} inside of a pubsub context"
  1032. );
  1033. }
  1034. }
  1035. }
  1036. /* ------------------------------------------------------------------------- */
  1037. class Predis_ConnectionParameters {
  1038. const DEFAULT_HOST = '127.0.0.1';
  1039. const DEFAULT_PORT = 6379;
  1040. const DEFAULT_TIMEOUT = 5;
  1041. private $_parameters;
  1042. public function __construct($parameters = null) {
  1043. $parameters = $parameters !== null ? $parameters : array();
  1044. $this->_parameters = is_array($parameters)
  1045. ? self::filterConnectionParams($parameters)
  1046. : self::parseURI($parameters);
  1047. }
  1048. private static function parseURI($uri) {
  1049. $parsed = @parse_url($uri);
  1050. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  1051. throw new Predis_ClientException("Invalid URI: $uri");
  1052. }
  1053. if (array_key_exists('query', $parsed)) {
  1054. $details = array();
  1055. foreach (explode('&', $parsed['query']) as $kv) {
  1056. list($k, $v) = explode('=', $kv);
  1057. switch ($k) {
  1058. case 'database':
  1059. $details['database'] = $v;
  1060. break;
  1061. case 'password':
  1062. $details['password'] = $v;
  1063. break;
  1064. case 'connection_async':
  1065. $details['connection_async'] = $v;
  1066. break;
  1067. case 'connection_persistent':
  1068. $details['connection_persistent'] = $v;
  1069. break;
  1070. case 'connection_timeout':
  1071. $details['connection_timeout'] = $v;
  1072. break;
  1073. case 'read_write_timeout':
  1074. $details['read_write_timeout'] = $v;
  1075. break;
  1076. case 'alias':
  1077. $details['alias'] = $v;
  1078. break;
  1079. case 'weight':
  1080. $details['weight'] = $v;
  1081. break;
  1082. }
  1083. }
  1084. $parsed = array_merge($parsed, $details);
  1085. }
  1086. return self::filterConnectionParams($parsed);
  1087. }
  1088. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  1089. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  1090. }
  1091. private static function filterConnectionParams($parameters) {
  1092. return array(
  1093. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  1094. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  1095. 'database' => self::getParamOrDefault($parameters, 'database'),
  1096. 'password' => self::getParamOrDefault($parameters, 'password'),
  1097. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  1098. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  1099. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  1100. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  1101. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  1102. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  1103. );
  1104. }
  1105. public function __get($parameter) {
  1106. return $this->_parameters[$parameter];
  1107. }
  1108. public function __isset($parameter) {
  1109. return isset($this->_parameters[$parameter]);
  1110. }
  1111. }
  1112. interface Predis_IConnection {
  1113. public function connect();
  1114. public function disconnect();
  1115. public function isConnected();
  1116. public function writeCommand(Predis_Command $command);
  1117. public function readResponse(Predis_Command $command);
  1118. public function executeCommand(Predis_Command $command);
  1119. }
  1120. class Predis_Connection implements Predis_IConnection {
  1121. private $_params, $_socket, $_initCmds, $_reader;
  1122. public function __construct(Predis_ConnectionParameters $parameters, Predis_ResponseReader $reader = null) {
  1123. $this->_params = $parameters;
  1124. $this->_initCmds = array();
  1125. $this->_reader = $reader !== null ? $reader : new Predis_ResponseReader();
  1126. }
  1127. public function __destruct() {
  1128. if (!$this->_params->connection_persistent) {
  1129. $this->disconnect();
  1130. }
  1131. }
  1132. public function isConnected() {
  1133. return is_resource($this->_socket);
  1134. }
  1135. public function connect() {
  1136. if ($this->isConnected()) {
  1137. throw new Predis_ClientException('Connection already estabilished');
  1138. }
  1139. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  1140. $connectFlags = STREAM_CLIENT_CONNECT;
  1141. if ($this->_params->connection_async) {
  1142. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  1143. }
  1144. if ($this->_params->connection_persistent) {
  1145. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1146. }
  1147. $this->_socket = @stream_socket_client(
  1148. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1149. );
  1150. if (!$this->_socket) {
  1151. $this->onCommunicationException(trim($errstr), $errno);
  1152. }
  1153. if (isset($this->_params->read_write_timeout)) {
  1154. $timeoutSeconds = floor($this->_params->read_write_timeout);
  1155. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  1156. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  1157. }
  1158. if (count($this->_initCmds) > 0){
  1159. $this->sendInitializationCommands();
  1160. }
  1161. }
  1162. public function disconnect() {
  1163. if ($this->isConnected()) {
  1164. fclose($this->_socket);
  1165. }
  1166. }
  1167. public function pushInitCommand(Predis_Command $command){
  1168. $this->_initCmds[] = $command;
  1169. }
  1170. private function sendInitializationCommands() {
  1171. foreach ($this->_initCmds as $command) {
  1172. $this->writeCommand($command);
  1173. }
  1174. foreach ($this->_initCmds as $command) {
  1175. $this->readResponse($command);
  1176. }
  1177. }
  1178. private function onCommunicationException($message, $code = null) {
  1179. Predis_Shared_Utils::onCommunicationException(
  1180. new Predis_CommunicationException($this, $message, $code)
  1181. );
  1182. }
  1183. public function writeCommand(Predis_Command $command) {
  1184. $this->writeBytes($command->invoke());
  1185. }
  1186. public function readResponse(Predis_Command $command) {
  1187. $response = $this->_reader->read($this);
  1188. return isset($response->skipParse) ? $response : $command->parseResponse($response);
  1189. }
  1190. public function executeCommand(Predis_Command $command) {
  1191. $this->writeCommand($command);
  1192. if ($command->closesConnection()) {
  1193. return $this->disconnect();
  1194. }
  1195. return $this->readResponse($command);
  1196. }
  1197. public function rawCommand($rawCommandData, $closesConnection = false) {
  1198. $this->writeBytes($rawCommandData);
  1199. if ($closesConnection) {
  1200. $this->disconnect();
  1201. return;
  1202. }
  1203. return $this->_reader->read($this);
  1204. }
  1205. public function writeBytes($value) {
  1206. $socket = $this->getSocket();
  1207. while (($length = strlen($value)) > 0) {
  1208. $written = fwrite($socket, $value);
  1209. if ($length === $written) {
  1210. return true;
  1211. }
  1212. if ($written === false || $written === 0) {
  1213. $this->onCommunicationException('Error while writing bytes to the server');
  1214. }
  1215. $value = substr($value, $written);
  1216. }
  1217. return true;
  1218. }
  1219. public function readBytes($length) {
  1220. if ($length <= 0) {
  1221. throw new InvalidArgumentException('Length parameter must be greater than 0');
  1222. }
  1223. $socket = $this->getSocket();
  1224. $value = '';
  1225. do {
  1226. $chunk = fread($socket, $length);
  1227. if ($chunk === false || $chunk === '') {
  1228. $this->onCommunicationException('Error while reading bytes from the server');
  1229. }
  1230. $value .= $chunk;
  1231. }
  1232. while (($length -= strlen($chunk)) > 0);
  1233. return $value;
  1234. }
  1235. public function readLine() {
  1236. $socket = $this->getSocket();
  1237. $value = '';
  1238. do {
  1239. $chunk = fgets($socket);
  1240. if ($chunk === false || $chunk === '') {
  1241. $this->onCommunicationException('Error while reading line from the server');
  1242. }
  1243. $value .= $chunk;
  1244. }
  1245. while (substr($value, -2) !== "\r\n");
  1246. return substr($value, 0, -2);
  1247. }
  1248. public function getSocket() {
  1249. if (!$this->isConnected()) {
  1250. $this->connect();
  1251. }
  1252. return $this->_socket;
  1253. }
  1254. public function getResponseReader() {
  1255. return $this->_reader;
  1256. }
  1257. public function getParameters() {
  1258. return $this->_params;
  1259. }
  1260. public function __toString() {
  1261. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  1262. }
  1263. }
  1264. class Predis_ConnectionCluster implements Predis_IConnection, IteratorAggregate {
  1265. private $_pool, $_distributor;
  1266. public function __construct(Predis_Distribution_IDistributionStrategy $distributor = null) {
  1267. $this->_pool = array();
  1268. $this->_distributor = $distributor !== null ? $distributor : new Predis_Distribution_HashRing();
  1269. }
  1270. public function isConnected() {
  1271. foreach ($this->_pool as $connection) {
  1272. if ($connection->isConnected()) {
  1273. return true;
  1274. }
  1275. }
  1276. return false;
  1277. }
  1278. public function connect() {
  1279. foreach ($this->_pool as $connection) {
  1280. $connection->connect();
  1281. }
  1282. }
  1283. public function disconnect() {
  1284. foreach ($this->_pool as $connection) {
  1285. $connection->disconnect();
  1286. }
  1287. }
  1288. public function add(Predis_Connection $connection) {
  1289. $parameters = $connection->getParameters();
  1290. if (isset($parameters->alias)) {
  1291. $this->_pool[$parameters->alias] = $connection;
  1292. }
  1293. else {
  1294. $this->_pool[] = $connection;
  1295. }
  1296. $this->_distributor->add($connection, $parameters->weight);
  1297. }
  1298. public function getConnection(Predis_Command $command) {
  1299. if ($command->canBeHashed() === false) {
  1300. throw new Predis_ClientException(
  1301. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1302. );
  1303. }
  1304. return $this->_distributor->get($command->getHash($this->_distributor));
  1305. }
  1306. public function getConnectionById($id = null) {
  1307. $alias = $id !== null ? $id : 0;
  1308. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1309. }
  1310. public function getIterator() {
  1311. return new ArrayIterator($this->_pool);
  1312. }
  1313. public function writeCommand(Predis_Command $command) {
  1314. $this->getConnection($command)->writeCommand($command);
  1315. }
  1316. public function readResponse(Predis_Command $command) {
  1317. return $this->getConnection($command)->readResponse($command);
  1318. }
  1319. public function executeCommand(Predis_Command $command) {
  1320. $connection = $this->getConnection($command);
  1321. $connection->writeCommand($command);
  1322. return $connection->readResponse($command);
  1323. }
  1324. }
  1325. /* ------------------------------------------------------------------------- */
  1326. abstract class Predis_RedisServerProfile {
  1327. private static $_serverProfiles;
  1328. private $_registeredCommands;
  1329. public function __construct() {
  1330. $this->_registeredCommands = $this->getSupportedCommands();
  1331. }
  1332. public abstract function getVersion();
  1333. protected abstract function getSupportedCommands();
  1334. public static function getDefault() {
  1335. return self::get('default');
  1336. }
  1337. public static function getDevelopment() {
  1338. return self::get('dev');
  1339. }
  1340. private static function predisServerProfiles() {
  1341. return array(
  1342. '1.2' => 'Predis_RedisServer_v1_2',
  1343. '2.0' => 'Predis_RedisServer_v2_0',
  1344. '2.2' => 'Predis_RedisServer_v2_2',
  1345. 'default' => 'Predis_RedisServer_v2_0',
  1346. 'dev' => 'Predis_RedisServer_vNext',
  1347. );
  1348. }
  1349. public static function registerProfile($profileClass, $aliases) {
  1350. if (!isset(self::$_serverProfiles)) {
  1351. self::$_serverProfiles = self::predisServerProfiles();
  1352. }
  1353. $profileReflection = new ReflectionClass($profileClass);
  1354. if (!$profileReflection->isSubclassOf('Predis_RedisServerProfile')) {
  1355. throw new Predis_ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1356. }
  1357. if (is_array($aliases)) {
  1358. foreach ($aliases as $alias) {
  1359. self::$_serverProfiles[$alias] = $profileClass;
  1360. }
  1361. }
  1362. else {
  1363. self::$_serverProfiles[$aliases] = $profileClass;
  1364. }
  1365. }
  1366. public static function get($version) {
  1367. if (!isset(self::$_serverProfiles)) {
  1368. self::$_serverProfiles = self::predisServerProfiles();
  1369. }
  1370. if (!isset(self::$_serverProfiles[$version])) {
  1371. throw new Predis_ClientException("Unknown server profile: $version");
  1372. }
  1373. $profile = self::$_serverProfiles[$version];
  1374. return new $profile();
  1375. }
  1376. public function supportsCommands(Array $commands) {
  1377. foreach ($commands as $command) {
  1378. if ($this->supportsCommand($command) === false) {
  1379. return false;
  1380. }
  1381. }
  1382. return true;
  1383. }
  1384. public function supportsCommand($command) {
  1385. return isset($this->_registeredCommands[$command]);
  1386. }
  1387. public function createCommand($method, $arguments = array()) {
  1388. if (!isset($this->_registeredCommands[$method])) {
  1389. throw new Predis_ClientException("'$method' is not a registered Redis command");
  1390. }
  1391. $commandClass = $this->_registeredCommands[$method];
  1392. $command = new $commandClass();
  1393. $command->setArgumentsArray($arguments);
  1394. return $command;
  1395. }
  1396. public function registerCommands(Array $commands) {
  1397. foreach ($commands as $command => $aliases) {
  1398. $this->registerCommand($command, $aliases);
  1399. }
  1400. }
  1401. public function registerCommand($command, $aliases) {
  1402. $commandReflection = new ReflectionClass($command);
  1403. if (!$commandReflection->isSubclassOf('Predis_Command')) {
  1404. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1405. }
  1406. if (is_array($aliases)) {
  1407. foreach ($aliases as $alias) {
  1408. $this->_registeredCommands[$alias] = $command;
  1409. }
  1410. }
  1411. else {
  1412. $this->_registeredCommands[$aliases] = $command;
  1413. }
  1414. }
  1415. public function __toString() {
  1416. return $this->getVersion();
  1417. }
  1418. }
  1419. class Predis_RedisServer_v1_2 extends Predis_RedisServerProfile {
  1420. public function getVersion() { return '1.2'; }
  1421. public function getSupportedCommands() {
  1422. return array(
  1423. /* miscellaneous commands */
  1424. 'ping' => 'Predis_Commands_Ping',
  1425. 'echo' => 'Predis_Commands_DoEcho',
  1426. 'auth' => 'Predis_Commands_Auth',
  1427. /* connection handling */
  1428. 'quit' => 'Predis_Commands_Quit',
  1429. /* commands operating on string values */
  1430. 'set' => 'Predis_Commands_Set',
  1431. 'setnx' => 'Predis_Commands_SetPreserve',
  1432. 'setPreserve' => 'Predis_Commands_SetPreserve',
  1433. 'mset' => 'Predis_Commands_SetMultiple',
  1434. 'setMultiple' => 'Predis_Commands_SetMultiple',
  1435. 'msetnx' => 'Predis_Commands_SetMultiplePreserve',
  1436. 'setMultiplePreserve' => 'Predis_Commands_SetMultiplePreserve',
  1437. 'get' => 'Predis_Commands_Get',
  1438. 'mget' => 'Predis_Commands_GetMultiple',
  1439. 'getMultiple' => 'Predis_Commands_GetMultiple',
  1440. 'getset' => 'Predis_Commands_GetSet',
  1441. 'getSet' => 'Predis_Commands_GetSet',
  1442. 'incr' => 'Predis_Commands_Increment',
  1443. 'increment' => 'Predis_Commands_Increment',
  1444. 'incrby' => 'Predis_Commands_IncrementBy',
  1445. 'incrementBy' => 'Predis_Commands_IncrementBy',
  1446. 'decr' => 'Predis_Commands_Decrement',
  1447. 'decrement' => 'Predis_Commands_Decrement',
  1448. 'decrby' => 'Predis_Commands_DecrementBy',
  1449. 'decrementBy' => 'Predis_Commands_DecrementBy',
  1450. 'exists' => 'Predis_Commands_Exists',
  1451. 'del' => 'Predis_Commands_Delete',
  1452. 'delete' => 'Predis_Commands_Delete',
  1453. 'type' => 'Predis_Commands_Type',
  1454. /* commands operating on the key space */
  1455. 'keys' => 'Predis_Commands_Keys_v1_2',
  1456. 'randomkey' => 'Predis_Commands_RandomKey',
  1457. 'randomKey' => 'Predis_Commands_RandomKey',
  1458. 'rename' => 'Predis_Commands_Rename',
  1459. 'renamenx' => 'Predis_Commands_RenamePreserve',
  1460. 'renamePreserve' => 'Predis_Commands_RenamePreserve',
  1461. 'expire' => 'Predis_Commands_Expire',
  1462. 'expireat' => 'Predis_Commands_ExpireAt',
  1463. 'expireAt' => 'Predis_Commands_ExpireAt',
  1464. 'dbsize' => 'Predis_Commands_DatabaseSize',
  1465. 'databaseSize' => 'Predis_Commands_DatabaseSize',
  1466. 'ttl' => 'Predis_Commands_TimeToLive',
  1467. 'timeToLive' => 'Predis_Commands_TimeToLive',
  1468. /* commands operating on lists */
  1469. 'rpush' => 'Predis_Commands_ListPushTail',
  1470. 'pushTail' => 'Predis_Commands_ListPushTail',
  1471. 'lpush' => 'Predis_Commands_ListPushHead',
  1472. 'pushHead' => 'Predis_Commands_ListPushHead',
  1473. 'llen' => 'Predis_Commands_ListLength',
  1474. 'listLength' => 'Predis_Commands_ListLength',
  1475. 'lrange' => 'Predis_Commands_ListRange',
  1476. 'listRange' => 'Predis_Commands_ListRange',
  1477. 'ltrim' => 'Predis_Commands_ListTrim',
  1478. 'listTrim' => 'Predis_Commands_ListTrim',
  1479. 'lindex' => 'Predis_Commands_ListIndex',
  1480. 'listIndex' => 'Predis_Commands_ListIndex',
  1481. 'lset' => 'Predis_Commands_ListSet',
  1482. 'listSet' => 'Predis_Commands_ListSet',
  1483. 'lrem' => 'Predis_Commands_ListRemove',
  1484. 'listRemove' => 'Predis_Commands_ListRemove',
  1485. 'lpop' => 'Predis_Commands_ListPopFirst',
  1486. 'popFirst' => 'Predis_Commands_ListPopFirst',
  1487. 'rpop' => 'Predis_Commands_ListPopLast',
  1488. 'popLast' => 'Predis_Commands_ListPopLast',
  1489. 'rpoplpush' => 'Predis_Commands_ListPopLastPushHead',
  1490. 'listPopLastPushHead' => 'Predis_Commands_ListPopLastPushHead',
  1491. /* commands operating on sets */
  1492. 'sadd' => 'Predis_Commands_SetAdd',
  1493. 'setAdd' => 'Predis_Commands_SetAdd',
  1494. 'srem' => 'Predis_Commands_SetRemove',
  1495. 'setRemove' => 'Predis_Commands_SetRemove',
  1496. 'spop' => 'Predis_Commands_SetPop',
  1497. 'setPop' => 'Predis_Commands_SetPop',
  1498. 'smove' => 'Predis_Commands_SetMove',
  1499. 'setMove' => 'Predis_Commands_SetMove',
  1500. 'scard' => 'Predis_Commands_SetCardinality',
  1501. 'setCardinality' => 'Predis_Commands_SetCardinality',
  1502. 'sismember' => 'Predis_Commands_SetIsMember',
  1503. 'setIsMember' => 'Predis_Commands_SetIsMember',
  1504. 'sinter' => 'Predis_Commands_SetIntersection',
  1505. 'setIntersection' => 'Predis_Commands_SetIntersection',
  1506. 'sinterstore' => 'Predis_Commands_SetIntersectionStore',
  1507. 'setIntersectionStore' => 'Predis_Commands_SetIntersectionStore',
  1508. 'sunion' => 'Predis_Commands_SetUnion',
  1509. 'setUnion' => 'Predis_Commands_SetUnion',
  1510. 'sunionstore' => 'Predis_Commands_SetUnionStore',
  1511. 'setUnionStore' => 'Predis_Commands_SetUnionStore',
  1512. 'sdiff' => 'Predis_Commands_SetDifference',
  1513. 'setDifference' => 'Predis_Commands_SetDifference',
  1514. 'sdiffstore' => 'Predis_Commands_SetDifferenceStore',
  1515. 'setDifferenceStore' => 'Predis_Commands_SetDifferenceStore',
  1516. 'smembers' => 'Predis_Commands_SetMembers',
  1517. 'setMembers' => 'Predis_Commands_SetMembers',
  1518. 'srandmember' => 'Predis_Commands_SetRandomMember',
  1519. 'setRandomMember' => 'Predis_Commands_SetRandomMember',
  1520. /* commands operating on sorted sets */
  1521. 'zadd' => 'Predis_Commands_ZSetAdd',
  1522. 'zsetAdd' => 'Predis_Commands_ZSetAdd',
  1523. 'zincrby' => 'Predis_Commands_ZSetIncrementBy',
  1524. 'zsetIncrementBy' => 'Predis_Commands_ZSetIncrementBy',
  1525. 'zrem' => 'Predis_Commands_ZSetRemove',
  1526. 'zsetRemove' => 'Predis_Commands_ZSetRemove',
  1527. 'zrange' => 'Predis_Commands_ZSetRange',
  1528. 'zsetRange' => 'Predis_Commands_ZSetRange',
  1529. 'zrevrange' => 'Predis_Commands_ZSetReverseRange',
  1530. 'zsetReverseRange' => 'Predis_Commands_ZSetReverseRange',
  1531. 'zrangebyscore' => 'Predis_Commands_ZSetRangeByScore',
  1532. 'zsetRangeByScore' => 'Predis_Commands_ZSetRangeByScore',
  1533. 'zcard' => 'Predis_Commands_ZSetCardinality',
  1534. 'zsetCardinality' => 'Predis_Commands_ZSetCardinality',
  1535. 'zscore' => 'Predis_Commands_ZSetScore',
  1536. 'zsetScore' => 'Predis_Commands_ZSetScore',
  1537. 'zremrangebyscore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  1538. 'zsetRemoveRangeByScore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  1539. /* multiple databases handling commands */
  1540. 'select' => 'Predis_Commands_SelectDatabase',
  1541. 'selectDatabase' => 'Predis_Commands_SelectDatabase',
  1542. 'move' => 'Predis_Commands_MoveKey',
  1543. 'moveKey' => 'Predis_Commands_MoveKey',
  1544. 'flushdb' => 'Predis_Commands_FlushDatabase',
  1545. 'flushDatabase' => 'Predis_Commands_FlushDatabase',
  1546. 'flushall' => 'Predis_Commands_FlushAll',
  1547. 'flushDatabases' => 'Predis_Commands_FlushAll',
  1548. /* sorting */
  1549. 'sort' => 'Predis_Commands_Sort',
  1550. /* remote server control commands */
  1551. 'info' => 'Predis_Commands_Info',
  1552. 'slaveof' => 'Predis_Commands_SlaveOf',
  1553. 'slaveOf' => 'Predis_Commands_SlaveOf',
  1554. /* persistence control commands */
  1555. 'save' => 'Predis_Commands_Save',
  1556. 'bgsave' => 'Predis_Commands_BackgroundSave',
  1557. 'backgroundSave' => 'Predis_Commands_BackgroundSave',
  1558. 'lastsave' => 'Predis_Commands_LastSave',
  1559. 'lastSave' => 'Predis_Commands_LastSave',
  1560. 'shutdown' => 'Predis_Commands_Shutdown',
  1561. 'bgrewriteaof' => 'Predis_Commands_BackgroundRewriteAppendOnlyFile',
  1562. 'backgroundRewriteAppendOnlyFile' => 'Predis_Commands_BackgroundRewriteAppendOnlyFile',
  1563. );
  1564. }
  1565. }
  1566. class Predis_RedisServer_v2_0 extends Predis_RedisServer_v1_2 {
  1567. public function getVersion() { return '2.0'; }
  1568. public function getSupportedCommands() {
  1569. return array_merge(parent::getSupportedCommands(), array(
  1570. /* transactions */
  1571. 'multi' => 'Predis_Commands_Multi',
  1572. 'exec' => 'Predis_Commands_Exec',
  1573. 'discard' => 'Predis_Commands_Discard',
  1574. /* commands operating on string values */
  1575. 'setex' => 'Predis_Commands_SetExpire',
  1576. 'setExpire' => 'Predis_Commands_SetExpire',
  1577. 'append' => 'Predis_Commands_Append',
  1578. 'substr' => 'Predis_Commands_Substr',
  1579. /* commands operating on the key space */
  1580. 'keys' => 'Predis_Commands_Keys',
  1581. /* commands operating on lists */
  1582. 'blpop' => 'Predis_Commands_ListPopFirstBlocking',
  1583. 'popFirstBlocking' => 'Predis_Commands_ListPopFirstBlocking',
  1584. 'brpop' => 'Predis_Commands_ListPopLastBlocking',
  1585. 'popLastBlocking' => 'Predis_Commands_ListPopLastBlocking',
  1586. /* commands operating on sorted sets */
  1587. 'zunionstore' => 'Predis_Commands_ZSetUnionStore',
  1588. 'zsetUnionStore' => 'Predis_Commands_ZSetUnionStore',
  1589. 'zinterstore' => 'Predis_Commands_ZSetIntersectionStore',
  1590. 'zsetIntersectionStore' => 'Predis_Commands_ZSetIntersectionStore',
  1591. 'zcount' => 'Predis_Commands_ZSetCount',
  1592. 'zsetCount' => 'Predis_Commands_ZSetCount',
  1593. 'zrank' => 'Predis_Commands_ZSetRank',
  1594. 'zsetRank' => 'Predis_Commands_ZSetRank',
  1595. 'zrevrank' => 'Predis_Commands_ZSetReverseRank',
  1596. 'zsetReverseRank' => 'Predis_Commands_ZSetReverseRank',
  1597. 'zremrangebyrank' => 'Predis_Commands_ZSetRemoveRangeByRank',
  1598. 'zsetRemoveRangeByRank' => 'Predis_Commands_ZSetRemoveRangeByRank',
  1599. /* commands operating on hashes */
  1600. 'hset' => 'Predis_Commands_HashSet',
  1601. 'hashSet' => 'Predis_Commands_HashSet',
  1602. 'hsetnx' => 'Predis_Commands_HashSetPreserve',
  1603. 'hashSetPreserve' => 'Predis_Commands_HashSetPreserve',
  1604. 'hmset' => 'Predis_Commands_HashSetMultiple',
  1605. 'hashSetMultiple' => 'Predis_Commands_HashSetMultiple',
  1606. 'hincrby' => 'Predis_Commands_HashIncrementBy',
  1607. 'hashIncrementBy' => 'Predis_Commands_HashIncrementBy',
  1608. 'hget' => 'Predis_Commands_HashGet',
  1609. 'hashGet' => 'Predis_Commands_HashGet',
  1610. 'hmget' => 'Predis_Commands_HashGetMultiple',
  1611. 'hashGetMultiple' => 'Predis_Commands_HashGetMultiple',
  1612. 'hdel' => 'Predis_Commands_HashDelete',
  1613. 'hashDelete' => 'Predis_Commands_HashDelete',
  1614. 'hexists' => 'Predis_Commands_HashExists',
  1615. 'hashExists' => 'Predis_Commands_HashExists',
  1616. 'hlen' => 'Predis_Commands_HashLength',
  1617. 'hashLength' => 'Predis_Commands_HashLength',
  1618. 'hkeys' => 'Predis_Commands_HashKeys',
  1619. 'hashKeys' => 'Predis_Commands_HashKeys',
  1620. 'hvals' => 'Predis_Commands_HashValues',
  1621. 'hashValues' => 'Predis_Commands_HashValues',
  1622. 'hgetall' => 'Predis_Commands_HashGetAll',
  1623. 'hashGetAll' => 'Predis_Commands_HashGetAll',
  1624. /* publish - subscribe */
  1625. 'subscribe' => 'Predis_Commands_Subscribe',
  1626. 'unsubscribe' => 'Predis_Commands_Unsubscribe',
  1627. 'psubscribe' => 'Predis_Commands_SubscribeByPattern',
  1628. 'punsubscribe' => 'Predis_Commands_UnsubscribeByPattern',
  1629. 'publish' => 'Predis_Commands_Publish',
  1630. /* remote server control commands */
  1631. 'config' => 'Predis_Commands_Config',
  1632. 'configuration' => 'Predis_Commands_Config',
  1633. ));
  1634. }
  1635. }
  1636. class Predis_RedisServer_v2_2 extends Predis_RedisServer_v2_0 {
  1637. public function getVersion() { return '2.2'; }
  1638. public function getSupportedCommands() {
  1639. return array_merge(parent::getSupportedCommands(), array(
  1640. /* transactions */
  1641. 'watch' => 'Predis_Commands_Watch',
  1642. 'unwatch' => 'Predis_Commands_Unwatch',
  1643. /* commands operating on string values */
  1644. 'strlen' => 'Predis_Commands_Strlen',
  1645. 'setrange' => 'Predis_Commands_SetRange',
  1646. 'getrange' => 'Predis_Commands_Substr',
  1647. 'setbit' => 'Predis_Commands_SetBit',
  1648. 'getbit' => 'Predis_Commands_GetBit',
  1649. /* commands operating on the key space */
  1650. 'persist' => 'Predis_Commands_Persist',
  1651. /* commands operating on lists */
  1652. 'rpushx' => 'Predis_Commands_ListPushTailX',
  1653. 'lpushx' => 'Predis_Commands_ListPushHeadX',
  1654. 'linsert' => 'Predis_Commands_ListInsert',
  1655. 'brpoplpush' => 'Predis_Commands_ListPopLastPushHeadBlocking',
  1656. /* commands operating on sorted sets */
  1657. 'zrevrangebyscore' => 'Predis_Commands_ZSetReverseRangeByScore',
  1658. ));
  1659. }
  1660. }
  1661. class Predis_RedisServer_vNext extends Predis_RedisServer_v2_2 {
  1662. public function getVersion() { return 'DEV'; }
  1663. }
  1664. /* ------------------------------------------------------------------------- */
  1665. interface Predis_Pipeline_IPipelineExecutor {
  1666. public function execute(Predis_IConnection $connection, &$commands);
  1667. }
  1668. class Predis_Pipeline_StandardExecutor implements Predis_Pipeline_IPipelineExecutor {
  1669. public function execute(Predis_IConnection $connection, &$commands) {
  1670. $sizeofPipe = count($commands);
  1671. $values = array();
  1672. foreach ($commands as $command) {
  1673. $connection->writeCommand($command);
  1674. }
  1675. try {
  1676. for ($i = 0; $i < $sizeofPipe; $i++) {
  1677. $response = $connection->readResponse($commands[$i]);
  1678. $values[] = $response instanceof Iterator
  1679. ? iterator_to_array($response)
  1680. : $response;
  1681. unset($commands[$i]);
  1682. }
  1683. }
  1684. catch (Predis_ServerException $exception) {
  1685. // force disconnection to prevent protocol desynchronization
  1686. $connection->disconnect();
  1687. throw $exception;
  1688. }
  1689. return $values;
  1690. }
  1691. }
  1692. class Predis_Pipeline_SafeExecutor implements Predis_Pipeline_IPipelineExecutor {
  1693. public function execute(Predis_IConnection $connection, &$commands) {
  1694. $sizeofPipe = count($commands);
  1695. $values = array();
  1696. foreach ($commands as $command) {
  1697. try {
  1698. $connection->writeCommand($command);
  1699. }
  1700. catch (Predis_CommunicationException $exception) {
  1701. return array_fill(0, $sizeofPipe, $exception);
  1702. }
  1703. }
  1704. for ($i = 0; $i < $sizeofPipe; $i++) {
  1705. $command = $commands[$i];
  1706. unset($commands[$i]);
  1707. try {
  1708. $response = $connection->readResponse($command);
  1709. $values[] = ($response instanceof Iterator
  1710. ? iterator_to_array($response)
  1711. : $response
  1712. );
  1713. }
  1714. catch (Predis_ServerException $exception) {
  1715. $values[] = $exception->toResponseError();
  1716. }
  1717. catch (Predis_CommunicationException $exception) {
  1718. $toAdd = count($commands) - count($values);
  1719. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  1720. break;
  1721. }
  1722. }
  1723. return $values;
  1724. }
  1725. }
  1726. class Predis_Pipeline_SafeClusterExecutor implements Predis_Pipeline_IPipelineExecutor {
  1727. public function execute(Predis_IConnection $connection, &$commands) {
  1728. $connectionExceptions = array();
  1729. $sizeofPipe = count($commands);
  1730. $values = array();
  1731. foreach ($commands as $command) {
  1732. $cmdConnection = $connection->getConnection($command);
  1733. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  1734. continue;
  1735. }
  1736. try {
  1737. $cmdConnection->writeCommand($command);
  1738. }
  1739. catch (Predis_CommunicationException $exception) {
  1740. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  1741. }
  1742. }
  1743. for ($i = 0; $i < $sizeofPipe; $i++) {
  1744. $command = $commands[$i];
  1745. unset($commands[$i]);
  1746. $cmdConnection = $connection->getConnection($command);
  1747. $connectionObjectHash = spl_object_hash($cmdConnection);
  1748. if (isset($connectionExceptions[$connectionObjectHash])) {
  1749. $values[] = $connectionExceptions[$connectionObjectHash];
  1750. continue;
  1751. }
  1752. try {
  1753. $response = $cmdConnection->readResponse($command);
  1754. $values[] = ($response instanceof Iterator
  1755. ? iterator_to_array($response)
  1756. : $response
  1757. );
  1758. }
  1759. catch (Predis_ServerException $exception) {
  1760. $values[] = $exception->toResponseError();
  1761. }
  1762. catch (Predis_CommunicationException $exception) {
  1763. $values[] = $exception;
  1764. $connectionExceptions[$connectionObjectHash] = $exception;
  1765. }
  1766. }
  1767. return $values;
  1768. }
  1769. }
  1770. /* ------------------------------------------------------------------------- */
  1771. interface Predis_Distribution_IDistributionStrategy {
  1772. public function add($node, $weight = null);
  1773. public function remove($node);
  1774. public function get($key);
  1775. public function generateKey($value);
  1776. }
  1777. class Predis_Distribution_EmptyRingException extends Exception { }
  1778. class Predis_Distribution_HashRing implements Predis_Distribution_IDistributionStrategy {
  1779. const DEFAULT_REPLICAS = 128;
  1780. const DEFAULT_WEIGHT = 100;
  1781. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1782. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1783. $this->_replicas = $replicas;
  1784. $this->_nodes = array();
  1785. }
  1786. public function add($node, $weight = null) {
  1787. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1788. // last wins, thus the order in which nodes are added is significant.
  1789. // TODO: self::DEFAULT_WEIGHT does not work for inherited classes that
  1790. // override the DEFAULT_WEIGHT constant.
  1791. $this->_nodes[] = array(
  1792. 'object' => $node,
  1793. 'weight' => (int) ($weight !== null ? $weight : self::DEFAULT_WEIGHT),
  1794. );
  1795. $this->reset();
  1796. }
  1797. public function remove($node) {
  1798. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1799. // scratch, in order to reassign possible hashes with collisions to the
  1800. // right node according to the order in which they were added in the
  1801. // first place.
  1802. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1803. if ($this->_nodes[$i]['object'] === $node) {
  1804. array_splice($this->_nodes, $i, 1);
  1805. $this->reset();
  1806. break;
  1807. }
  1808. }
  1809. }
  1810. private function reset() {
  1811. unset($this->_ring);
  1812. unset($this->_ringKeys);
  1813. unset($this->_ringKeysCount);
  1814. }
  1815. private function isInitialized() {
  1816. return isset($this->_ringKeys);
  1817. }
  1818. private function computeTotalWeight() {
  1819. $totalWeight = 0;
  1820. foreach ($this->_nodes as $node) {
  1821. $totalWeight += $node['weight'];
  1822. }
  1823. return $totalWeight;
  1824. }
  1825. private function initialize() {
  1826. if ($this->isInitialized()) {
  1827. return;
  1828. }
  1829. if (count($this->_nodes) === 0) {
  1830. throw new Predis_Distribution_EmptyRingException('Cannot initialize empty hashring');
  1831. }
  1832. $this->_ring = array();
  1833. $totalWeight = $this->computeTotalWeight();
  1834. $nodesCount = count($this->_nodes);
  1835. foreach ($this->_nodes as $node) {
  1836. $weightRatio = $node['weight'] / $totalWeight;
  1837. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1838. }
  1839. ksort($this->_ring, SORT_NUMERIC);
  1840. $this->_ringKeys = array_keys($this->_ring);
  1841. $this->_ringKeysCount = count($this->_ringKeys);
  1842. }
  1843. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1844. $nodeObject = $node['object'];
  1845. $nodeHash = (string) $nodeObject;
  1846. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1847. for ($i = 0; $i < $replicas; $i++) {
  1848. $key = crc32("$nodeHash:$i");
  1849. $ring[$key] = $nodeObject;
  1850. }
  1851. }
  1852. public function generateKey($value) {
  1853. return crc32($value);
  1854. }
  1855. public function get($key) {
  1856. return $this->_ring[$this->getNodeKey($key)];
  1857. }
  1858. private function getNodeKey($key) {
  1859. $this->initialize();
  1860. $ringKeys = $this->_ringKeys;
  1861. $upper = $this->_ringKeysCount - 1;
  1862. $lower = 0;
  1863. while ($lower <= $upper) {
  1864. $index = ($lower + $upper) >> 1;
  1865. $item = $ringKeys[$index];
  1866. if ($item > $key) {
  1867. $upper = $index - 1;
  1868. }
  1869. else if ($item < $key) {
  1870. $lower = $index + 1;
  1871. }
  1872. else {
  1873. return $item;
  1874. }
  1875. }
  1876. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1877. }
  1878. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1879. // NOTE: binary search for the last item in _ringkeys with a value
  1880. // less or equal to the key. If no such item exists, return the
  1881. // last item.
  1882. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1883. }
  1884. }
  1885. class Predis_Distribution_KetamaPureRing extends Predis_Distribution_HashRing {
  1886. const DEFAULT_REPLICAS = 160;
  1887. public function __construct() {
  1888. parent::__construct(self::DEFAULT_REPLICAS);
  1889. }
  1890. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1891. $nodeObject = $node['object'];
  1892. $nodeHash = (string) $nodeObject;
  1893. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1894. for ($i = 0; $i < $replicas; $i++) {
  1895. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1896. foreach ($unpackedDigest as $key) {
  1897. $ring[$key] = $nodeObject;
  1898. }
  1899. }
  1900. }
  1901. public function generateKey($value) {
  1902. $hash = unpack('V', md5($value, true));
  1903. return $hash[1];
  1904. }
  1905. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1906. // NOTE: binary search for the first item in _ringkeys with a value
  1907. // greater or equal to the key. If no such item exists, return the
  1908. // first item.
  1909. return $lower < $ringKeysCount ? $lower : 0;
  1910. }
  1911. }
  1912. /* ------------------------------------------------------------------------- */
  1913. class Predis_Shared_Utils {
  1914. public static function isCluster(Predis_IConnection $connection) {
  1915. return $connection instanceof Predis_ConnectionCluster;
  1916. }
  1917. public static function onCommunicationException(Predis_CommunicationException $exception) {
  1918. if ($exception->shouldResetConnection()) {
  1919. $connection = $exception->getConnection();
  1920. if ($connection->isConnected()) {
  1921. $connection->disconnect();
  1922. }
  1923. }
  1924. throw $exception;
  1925. }
  1926. }
  1927. abstract class Predis_Shared_MultiBulkResponseIteratorBase implements Iterator, Countable {
  1928. protected $_position, $_current, $_replySize;
  1929. public function rewind() {
  1930. // NOOP
  1931. }
  1932. public function current() {
  1933. return $this->_current;
  1934. }
  1935. public function key() {
  1936. return $this->_position;
  1937. }
  1938. public function next() {
  1939. if (++$this->_position < $this->_replySize) {
  1940. $this->_current = $this->getValue();
  1941. }
  1942. return $this->_position;
  1943. }
  1944. public function valid() {
  1945. return $this->_position < $this->_replySize;
  1946. }
  1947. public function count() {
  1948. // NOTE: use count if you want to get the size of the current multi-bulk
  1949. // response without using iterator_count (which actually consumes
  1950. // our iterator to calculate the size, and we cannot perform a rewind)
  1951. return $this->_replySize;
  1952. }
  1953. protected abstract function getValue();
  1954. }
  1955. class Predis_Shared_MultiBulkResponseIterator extends Predis_Shared_MultiBulkResponseIteratorBase {
  1956. private $_connection;
  1957. public function __construct(Predis_Connection $connection, $size) {
  1958. $this->_connection = $connection;
  1959. $this->_reader = $connection->getResponseReader();
  1960. $this->_position = 0;
  1961. $this->_current = $size > 0 ? $this->getValue() : null;
  1962. $this->_replySize = $size;
  1963. }
  1964. public function __destruct() {
  1965. // when the iterator is garbage-collected (e.g. it goes out of the
  1966. // scope of a foreach) but it has not reached its end, we must sync
  1967. // the client with the queued elements that have not been read from
  1968. // the connection with the server.
  1969. $this->sync();
  1970. }
  1971. public function sync($drop = false) {
  1972. if ($drop == true) {
  1973. if ($this->valid()) {
  1974. $this->_position = $this->_replySize;
  1975. $this->_connection->disconnect();
  1976. }
  1977. }
  1978. else {
  1979. while ($this->valid()) {
  1980. $this->next();
  1981. }
  1982. }
  1983. }
  1984. protected function getValue() {
  1985. return $this->_reader->read($this->_connection);
  1986. }
  1987. }
  1988. class Predis_Shared_MultiBulkResponseKVIterator extends Predis_Shared_MultiBulkResponseIteratorBase {
  1989. private $_iterator;
  1990. public function __construct(Predis_Shared_MultiBulkResponseIterator $iterator) {
  1991. $virtualSize = count($iterator) / 2;
  1992. $this->_iterator = $iterator;
  1993. $this->_position = 0;
  1994. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1995. $this->_replySize = $virtualSize;
  1996. }
  1997. public function __destruct() {
  1998. $this->_iterator->sync();
  1999. }
  2000. protected function getValue() {
  2001. $k = $this->_iterator->current();
  2002. $this->_iterator->next();
  2003. $v = $this->_iterator->current();
  2004. $this->_iterator->next();
  2005. return array($k, $v);
  2006. }
  2007. }
  2008. /* ------------------------------------------------------------------------- */
  2009. /* miscellaneous commands */
  2010. class Predis_Commands_Ping extends Predis_MultiBulkCommand {
  2011. public function canBeHashed() { return false; }
  2012. public function getCommandId() { return 'PING'; }
  2013. public function parseResponse($data) {
  2014. return $data === 'PONG' ? true : false;
  2015. }
  2016. }
  2017. class Predis_Commands_DoEcho extends Predis_MultiBulkCommand {
  2018. public function canBeHashed() { return false; }
  2019. public function getCommandId() { return 'ECHO'; }
  2020. }
  2021. class Predis_Commands_Auth extends Predis_MultiBulkCommand {
  2022. public function canBeHashed() { return false; }
  2023. public function getCommandId() { return 'AUTH'; }
  2024. }
  2025. /* connection handling */
  2026. class Predis_Commands_Quit extends Predis_MultiBulkCommand {
  2027. public function canBeHashed() { return false; }
  2028. public function getCommandId() { return 'QUIT'; }
  2029. public function closesConnection() { return true; }
  2030. }
  2031. /* commands operating on string values */
  2032. class Predis_Commands_Set extends Predis_MultiBulkCommand {
  2033. public function getCommandId() { return 'SET'; }
  2034. }
  2035. class Predis_Commands_SetExpire extends Predis_MultiBulkCommand {
  2036. public function getCommandId() { return 'SETEX'; }
  2037. }
  2038. class Predis_Commands_SetPreserve extends Predis_MultiBulkCommand {
  2039. public function getCommandId() { return 'SETNX'; }
  2040. public function parseResponse($data) { return (bool) $data; }
  2041. }
  2042. class Predis_Commands_SetMultiple extends Predis_MultiBulkCommand {
  2043. public function canBeHashed() { return false; }
  2044. public function getCommandId() { return 'MSET'; }
  2045. public function filterArguments(Array $arguments) {
  2046. if (count($arguments) === 1 && is_array($arguments[0])) {
  2047. $flattenedKVs = array();
  2048. $args = &$arguments[0];
  2049. foreach ($args as $k => $v) {
  2050. $flattenedKVs[] = $k;
  2051. $flattenedKVs[] = $v;
  2052. }
  2053. return $flattenedKVs;
  2054. }
  2055. return $arguments;
  2056. }
  2057. }
  2058. class Predis_Commands_SetMultiplePreserve extends Predis_Commands_SetMultiple {
  2059. public function canBeHashed() { return false; }
  2060. public function getCommandId() { return 'MSETNX'; }
  2061. public function parseResponse($data) { return (bool) $data; }
  2062. }
  2063. class Predis_Commands_Get extends Predis_MultiBulkCommand {
  2064. public function getCommandId() { return 'GET'; }
  2065. }
  2066. class Predis_Commands_GetMultiple extends Predis_MultiBulkCommand {
  2067. public function canBeHashed() { return false; }
  2068. public function getCommandId() { return 'MGET'; }
  2069. }
  2070. class Predis_Commands_GetSet extends Predis_MultiBulkCommand {
  2071. public function getCommandId() { return 'GETSET'; }
  2072. }
  2073. class Predis_Commands_Increment extends Predis_MultiBulkCommand {
  2074. public function getCommandId() { return 'INCR'; }
  2075. }
  2076. class Predis_Commands_IncrementBy extends Predis_MultiBulkCommand {
  2077. public function getCommandId() { return 'INCRBY'; }
  2078. }
  2079. class Predis_Commands_Decrement extends Predis_MultiBulkCommand {
  2080. public function getCommandId() { return 'DECR'; }
  2081. }
  2082. class Predis_Commands_DecrementBy extends Predis_MultiBulkCommand {
  2083. public function getCommandId() { return 'DECRBY'; }
  2084. }
  2085. class Predis_Commands_Exists extends Predis_MultiBulkCommand {
  2086. public function getCommandId() { return 'EXISTS'; }
  2087. public function parseResponse($data) { return (bool) $data; }
  2088. }
  2089. class Predis_Commands_Delete extends Predis_MultiBulkCommand {
  2090. public function getCommandId() { return 'DEL'; }
  2091. }
  2092. class Predis_Commands_Type extends Predis_MultiBulkCommand {
  2093. public function getCommandId() { return 'TYPE'; }
  2094. }
  2095. class Predis_Commands_Append extends Predis_MultiBulkCommand {
  2096. public function getCommandId() { return 'APPEND'; }
  2097. }
  2098. class Predis_Commands_SetRange extends Predis_MultiBulkCommand {
  2099. public function getCommandId() { return 'SETRANGE'; }
  2100. }
  2101. class Predis_Commands_Substr extends Predis_MultiBulkCommand {
  2102. public function getCommandId() { return 'SUBSTR'; }
  2103. }
  2104. class Predis_Commands_SetBit extends Predis_MultiBulkCommand {
  2105. public function getCommandId() { return 'SETBIT'; }
  2106. }
  2107. class Predis_Commands_GetBit extends Predis_MultiBulkCommand {
  2108. public function getCommandId() { return 'GETBIT'; }
  2109. }
  2110. class Predis_Commands_Strlen extends Predis_MultiBulkCommand {
  2111. public function getCommandId() { return 'STRLEN'; }
  2112. }
  2113. /* commands operating on the key space */
  2114. class Predis_Commands_Keys extends Predis_MultiBulkCommand {
  2115. public function canBeHashed() { return false; }
  2116. public function getCommandId() { return 'KEYS'; }
  2117. }
  2118. class Predis_Commands_Keys_v1_2 extends Predis_Commands_Keys {
  2119. public function parseResponse($data) {
  2120. return explode(' ', $data);
  2121. }
  2122. }
  2123. class Predis_Commands_RandomKey extends Predis_MultiBulkCommand {
  2124. public function canBeHashed() { return false; }
  2125. public function getCommandId() { return 'RANDOMKEY'; }
  2126. public function parseResponse($data) { return $data !== '' ? $data : null; }
  2127. }
  2128. class Predis_Commands_Rename extends Predis_MultiBulkCommand {
  2129. public function canBeHashed() { return false; }
  2130. public function getCommandId() { return 'RENAME'; }
  2131. }
  2132. class Predis_Commands_RenamePreserve extends Predis_MultiBulkCommand {
  2133. public function canBeHashed() { return false; }
  2134. public function getCommandId() { return 'RENAMENX'; }
  2135. public function parseResponse($data) { return (bool) $data; }
  2136. }
  2137. class Predis_Commands_Expire extends Predis_MultiBulkCommand {
  2138. public function getCommandId() { return 'EXPIRE'; }
  2139. public function parseResponse($data) { return (bool) $data; }
  2140. }
  2141. class Predis_Commands_ExpireAt extends Predis_MultiBulkCommand {
  2142. public function getCommandId() { return 'EXPIREAT'; }
  2143. public function parseResponse($data) { return (bool) $data; }
  2144. }
  2145. class Predis_Commands_Persist extends Predis_MultiBulkCommand {
  2146. public function getCommandId() { return 'PERSIST'; }
  2147. public function parseResponse($data) { return (bool) $data; }
  2148. }
  2149. class Predis_Commands_DatabaseSize extends Predis_MultiBulkCommand {
  2150. public function canBeHashed() { return false; }
  2151. public function getCommandId() { return 'DBSIZE'; }
  2152. }
  2153. class Predis_Commands_TimeToLive extends Predis_MultiBulkCommand {
  2154. public function getCommandId() { return 'TTL'; }
  2155. }
  2156. /* commands operating on lists */
  2157. class Predis_Commands_ListPushTail extends Predis_MultiBulkCommand {
  2158. public function getCommandId() { return 'RPUSH'; }
  2159. }
  2160. class Predis_Commands_ListPushTailX extends Predis_MultiBulkCommand {
  2161. public function getCommandId() { return 'RPUSHX'; }
  2162. }
  2163. class Predis_Commands_ListPushHead extends Predis_MultiBulkCommand {
  2164. public function getCommandId() { return 'LPUSH'; }
  2165. }
  2166. class Predis_Commands_ListPushHeadX extends Predis_MultiBulkCommand {
  2167. public function getCommandId() { return 'LPUSHX'; }
  2168. }
  2169. class Predis_Commands_ListLength extends Predis_MultiBulkCommand {
  2170. public function getCommandId() { return 'LLEN'; }
  2171. }
  2172. class Predis_Commands_ListRange extends Predis_MultiBulkCommand {
  2173. public function getCommandId() { return 'LRANGE'; }
  2174. }
  2175. class Predis_Commands_ListTrim extends Predis_MultiBulkCommand {
  2176. public function getCommandId() { return 'LTRIM'; }
  2177. }
  2178. class Predis_Commands_ListIndex extends Predis_MultiBulkCommand {
  2179. public function getCommandId() { return 'LINDEX'; }
  2180. }
  2181. class Predis_Commands_ListSet extends Predis_MultiBulkCommand {
  2182. public function getCommandId() { return 'LSET'; }
  2183. }
  2184. class Predis_Commands_ListRemove extends Predis_MultiBulkCommand {
  2185. public function getCommandId() { return 'LREM'; }
  2186. }
  2187. class Predis_Commands_ListPopLastPushHead extends Predis_MultiBulkCommand {
  2188. public function getCommandId() { return 'RPOPLPUSH'; }
  2189. }
  2190. class Predis_Commands_ListPopLastPushHeadBlocking extends Predis_MultiBulkCommand {
  2191. public function getCommandId() { return 'BRPOPLPUSH'; }
  2192. }
  2193. class Predis_Commands_ListPopFirst extends Predis_MultiBulkCommand {
  2194. public function getCommandId() { return 'LPOP'; }
  2195. }
  2196. class Predis_Commands_ListPopLast extends Predis_MultiBulkCommand {
  2197. public function getCommandId() { return 'RPOP'; }
  2198. }
  2199. class Predis_Commands_ListPopFirstBlocking extends Predis_MultiBulkCommand {
  2200. public function getCommandId() { return 'BLPOP'; }
  2201. }
  2202. class Predis_Commands_ListPopLastBlocking extends Predis_MultiBulkCommand {
  2203. public function getCommandId() { return 'BRPOP'; }
  2204. }
  2205. class Predis_Commands_ListInsert extends Predis_MultiBulkCommand {
  2206. public function getCommandId() { return 'LINSERT'; }
  2207. }
  2208. /* commands operating on sets */
  2209. class Predis_Commands_SetAdd extends Predis_MultiBulkCommand {
  2210. public function getCommandId() { return 'SADD'; }
  2211. public function parseResponse($data) { return (bool) $data; }
  2212. }
  2213. class Predis_Commands_SetRemove extends Predis_MultiBulkCommand {
  2214. public function getCommandId() { return 'SREM'; }
  2215. public function parseResponse($data) { return (bool) $data; }
  2216. }
  2217. class Predis_Commands_SetPop extends Predis_MultiBulkCommand {
  2218. public function getCommandId() { return 'SPOP'; }
  2219. }
  2220. class Predis_Commands_SetMove extends Predis_MultiBulkCommand {
  2221. public function canBeHashed() { return false; }
  2222. public function getCommandId() { return 'SMOVE'; }
  2223. public function parseResponse($data) { return (bool) $data; }
  2224. }
  2225. class Predis_Commands_SetCardinality extends Predis_MultiBulkCommand {
  2226. public function getCommandId() { return 'SCARD'; }
  2227. }
  2228. class Predis_Commands_SetIsMember extends Predis_MultiBulkCommand {
  2229. public function getCommandId() { return 'SISMEMBER'; }
  2230. public function parseResponse($data) { return (bool) $data; }
  2231. }
  2232. class Predis_Commands_SetIntersection extends Predis_MultiBulkCommand {
  2233. public function getCommandId() { return 'SINTER'; }
  2234. }
  2235. class Predis_Commands_SetIntersectionStore extends Predis_MultiBulkCommand {
  2236. public function getCommandId() { return 'SINTERSTORE'; }
  2237. }
  2238. class Predis_Commands_SetUnion extends Predis_MultiBulkCommand {
  2239. public function getCommandId() { return 'SUNION'; }
  2240. }
  2241. class Predis_Commands_SetUnionStore extends Predis_MultiBulkCommand {
  2242. public function getCommandId() { return 'SUNIONSTORE'; }
  2243. }
  2244. class Predis_Commands_SetDifference extends Predis_MultiBulkCommand {
  2245. public function getCommandId() { return 'SDIFF'; }
  2246. }
  2247. class Predis_Commands_SetDifferenceStore extends Predis_MultiBulkCommand {
  2248. public function getCommandId() { return 'SDIFFSTORE'; }
  2249. }
  2250. class Predis_Commands_SetMembers extends Predis_MultiBulkCommand {
  2251. public function getCommandId() { return 'SMEMBERS'; }
  2252. }
  2253. class Predis_Commands_SetRandomMember extends Predis_MultiBulkCommand {
  2254. public function getCommandId() { return 'SRANDMEMBER'; }
  2255. }
  2256. /* commands operating on sorted sets */
  2257. class Predis_Commands_ZSetAdd extends Predis_MultiBulkCommand {
  2258. public function getCommandId() { return 'ZADD'; }
  2259. public function parseResponse($data) { return (bool) $data; }
  2260. }
  2261. class Predis_Commands_ZSetIncrementBy extends Predis_MultiBulkCommand {
  2262. public function getCommandId() { return 'ZINCRBY'; }
  2263. }
  2264. class Predis_Commands_ZSetRemove extends Predis_MultiBulkCommand {
  2265. public function getCommandId() { return 'ZREM'; }
  2266. public function parseResponse($data) { return (bool) $data; }
  2267. }
  2268. class Predis_Commands_ZSetUnionStore extends Predis_MultiBulkCommand {
  2269. public function getCommandId() { return 'ZUNIONSTORE'; }
  2270. public function filterArguments(Array $arguments) {
  2271. $options = array();
  2272. $argc = count($arguments);
  2273. if ($argc > 1 && is_array($arguments[$argc - 1])) {
  2274. $options = $this->prepareOptions(array_pop($arguments));
  2275. }
  2276. $args = is_array($arguments[0]) ? $arguments[0] : $arguments;
  2277. return array_merge($args, $options);
  2278. }
  2279. private function prepareOptions($options) {
  2280. $opts = array_change_key_case($options, CASE_UPPER);
  2281. $finalizedOpts = array();
  2282. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  2283. $finalizedOpts[] = 'WEIGHTS';
  2284. foreach ($opts['WEIGHTS'] as $weight) {
  2285. $finalizedOpts[] = $weight;
  2286. }
  2287. }
  2288. if (isset($opts['AGGREGATE'])) {
  2289. $finalizedOpts[] = 'AGGREGATE';
  2290. $finalizedOpts[] = $opts['AGGREGATE'];
  2291. }
  2292. return $finalizedOpts;
  2293. }
  2294. }
  2295. class Predis_Commands_ZSetIntersectionStore extends Predis_Commands_ZSetUnionStore {
  2296. public function getCommandId() { return 'ZINTERSTORE'; }
  2297. }
  2298. class Predis_Commands_ZSetRange extends Predis_MultiBulkCommand {
  2299. private $_withScores = false;
  2300. public function getCommandId() { return 'ZRANGE'; }
  2301. public function filterArguments(Array $arguments) {
  2302. if (count($arguments) === 4) {
  2303. $lastType = gettype($arguments[3]);
  2304. if ($lastType === 'string' && strtolower($arguments[3]) === 'withscores') {
  2305. // used for compatibility with older versions
  2306. $arguments[3] = array('WITHSCORES' => true);
  2307. $lastType = 'array';
  2308. }
  2309. if ($lastType === 'array') {
  2310. $options = $this->prepareOptions(array_pop($arguments));
  2311. return array_merge($arguments, $options);
  2312. }
  2313. }
  2314. return $arguments;
  2315. }
  2316. protected function prepareOptions($options) {
  2317. $opts = array_change_key_case($options, CASE_UPPER);
  2318. $finalizedOpts = array();
  2319. if (isset($opts['WITHSCORES'])) {
  2320. $finalizedOpts[] = 'WITHSCORES';
  2321. $this->_withScores = true;
  2322. }
  2323. return $finalizedOpts;
  2324. }
  2325. public function parseResponse($data) {
  2326. if ($this->_withScores) {
  2327. if ($data instanceof Iterator) {
  2328. return new Predis_Shared_MultiBulkResponseKVIterator($data);
  2329. }
  2330. $result = array();
  2331. for ($i = 0; $i < count($data); $i++) {
  2332. $result[] = array($data[$i], $data[++$i]);
  2333. }
  2334. return $result;
  2335. }
  2336. return $data;
  2337. }
  2338. }
  2339. class Predis_Commands_ZSetReverseRange extends Predis_Commands_ZSetRange {
  2340. public function getCommandId() { return 'ZREVRANGE'; }
  2341. }
  2342. class Predis_Commands_ZSetRangeByScore extends Predis_Commands_ZSetRange {
  2343. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  2344. protected function prepareOptions($options) {
  2345. $opts = array_change_key_case($options, CASE_UPPER);
  2346. $finalizedOpts = array();
  2347. if (isset($opts['LIMIT']) && is_array($opts['LIMIT'])) {
  2348. $limit = array_change_key_case($opts['LIMIT'], CASE_UPPER);
  2349. $finalizedOpts[] = 'LIMIT';
  2350. $finalizedOpts[] = isset($limit['OFFSET']) ? $limit['OFFSET'] : $limit[0];
  2351. $finalizedOpts[] = isset($limit['COUNT']) ? $limit['COUNT'] : $limit[1];
  2352. }
  2353. return array_merge($finalizedOpts, parent::prepareOptions($options));
  2354. }
  2355. }
  2356. class Predis_Commands_ZSetReverseRangeByScore extends Predis_Commands_ZSetRangeByScore {
  2357. public function getCommandId() { return 'ZREVRANGEBYSCORE'; }
  2358. }
  2359. class Predis_Commands_ZSetCount extends Predis_MultiBulkCommand {
  2360. public function getCommandId() { return 'ZCOUNT'; }
  2361. }
  2362. class Predis_Commands_ZSetCardinality extends Predis_MultiBulkCommand {
  2363. public function getCommandId() { return 'ZCARD'; }
  2364. }
  2365. class Predis_Commands_ZSetScore extends Predis_MultiBulkCommand {
  2366. public function getCommandId() { return 'ZSCORE'; }
  2367. }
  2368. class Predis_Commands_ZSetRemoveRangeByScore extends Predis_MultiBulkCommand {
  2369. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  2370. }
  2371. class Predis_Commands_ZSetRank extends Predis_MultiBulkCommand {
  2372. public function getCommandId() { return 'ZRANK'; }
  2373. }
  2374. class Predis_Commands_ZSetReverseRank extends Predis_MultiBulkCommand {
  2375. public function getCommandId() { return 'ZREVRANK'; }
  2376. }
  2377. class Predis_Commands_ZSetRemoveRangeByRank extends Predis_MultiBulkCommand {
  2378. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  2379. }
  2380. /* commands operating on hashes */
  2381. class Predis_Commands_HashSet extends Predis_MultiBulkCommand {
  2382. public function getCommandId() { return 'HSET'; }
  2383. public function parseResponse($data) { return (bool) $data; }
  2384. }
  2385. class Predis_Commands_HashSetPreserve extends Predis_MultiBulkCommand {
  2386. public function getCommandId() { return 'HSETNX'; }
  2387. public function parseResponse($data) { return (bool) $data; }
  2388. }
  2389. class Predis_Commands_HashSetMultiple extends Predis_MultiBulkCommand {
  2390. public function getCommandId() { return 'HMSET'; }
  2391. public function filterArguments(Array $arguments) {
  2392. if (count($arguments) === 2 && is_array($arguments[1])) {
  2393. $flattenedKVs = array($arguments[0]);
  2394. $args = &$arguments[1];
  2395. foreach ($args as $k => $v) {
  2396. $flattenedKVs[] = $k;
  2397. $flattenedKVs[] = $v;
  2398. }
  2399. return $flattenedKVs;
  2400. }
  2401. return $arguments;
  2402. }
  2403. }
  2404. class Predis_Commands_HashIncrementBy extends Predis_MultiBulkCommand {
  2405. public function getCommandId() { return 'HINCRBY'; }
  2406. }
  2407. class Predis_Commands_HashGet extends Predis_MultiBulkCommand {
  2408. public function getCommandId() { return 'HGET'; }
  2409. }
  2410. class Predis_Commands_HashGetMultiple extends Predis_MultiBulkCommand {
  2411. public function getCommandId() { return 'HMGET'; }
  2412. public function filterArguments(Array $arguments) {
  2413. if (count($arguments) === 2 && is_array($arguments[1])) {
  2414. $flattenedKVs = array($arguments[0]);
  2415. $args = &$arguments[1];
  2416. foreach ($args as $v) {
  2417. $flattenedKVs[] = $v;
  2418. }
  2419. return $flattenedKVs;
  2420. }
  2421. return $arguments;
  2422. }
  2423. }
  2424. class Predis_Commands_HashDelete extends Predis_MultiBulkCommand {
  2425. public function getCommandId() { return 'HDEL'; }
  2426. public function parseResponse($data) { return (bool) $data; }
  2427. }
  2428. class Predis_Commands_HashExists extends Predis_MultiBulkCommand {
  2429. public function getCommandId() { return 'HEXISTS'; }
  2430. public function parseResponse($data) { return (bool) $data; }
  2431. }
  2432. class Predis_Commands_HashLength extends Predis_MultiBulkCommand {
  2433. public function getCommandId() { return 'HLEN'; }
  2434. }
  2435. class Predis_Commands_HashKeys extends Predis_MultiBulkCommand {
  2436. public function getCommandId() { return 'HKEYS'; }
  2437. }
  2438. class Predis_Commands_HashValues extends Predis_MultiBulkCommand {
  2439. public function getCommandId() { return 'HVALS'; }
  2440. }
  2441. class Predis_Commands_HashGetAll extends Predis_MultiBulkCommand {
  2442. public function getCommandId() { return 'HGETALL'; }
  2443. public function parseResponse($data) {
  2444. if ($data instanceof Iterator) {
  2445. return new Predis_Shared_MultiBulkResponseKVIterator($data);
  2446. }
  2447. $result = array();
  2448. for ($i = 0; $i < count($data); $i++) {
  2449. $result[$data[$i]] = $data[++$i];
  2450. }
  2451. return $result;
  2452. }
  2453. }
  2454. /* multiple databases handling commands */
  2455. class Predis_Commands_SelectDatabase extends Predis_MultiBulkCommand {
  2456. public function canBeHashed() { return false; }
  2457. public function getCommandId() { return 'SELECT'; }
  2458. }
  2459. class Predis_Commands_MoveKey extends Predis_MultiBulkCommand {
  2460. public function canBeHashed() { return false; }
  2461. public function getCommandId() { return 'MOVE'; }
  2462. public function parseResponse($data) { return (bool) $data; }
  2463. }
  2464. class Predis_Commands_FlushDatabase extends Predis_MultiBulkCommand {
  2465. public function canBeHashed() { return false; }
  2466. public function getCommandId() { return 'FLUSHDB'; }
  2467. }
  2468. class Predis_Commands_FlushAll extends Predis_MultiBulkCommand {
  2469. public function canBeHashed() { return false; }
  2470. public function getCommandId() { return 'FLUSHALL'; }
  2471. }
  2472. /* sorting */
  2473. class Predis_Commands_Sort extends Predis_MultiBulkCommand {
  2474. public function getCommandId() { return 'SORT'; }
  2475. public function filterArguments(Array $arguments) {
  2476. if (count($arguments) === 1) {
  2477. return $arguments;
  2478. }
  2479. $query = array($arguments[0]);
  2480. $sortParams = array_change_key_case($arguments[1], CASE_UPPER);
  2481. if (isset($sortParams['BY'])) {
  2482. $query[] = 'BY';
  2483. $query[] = $sortParams['BY'];
  2484. }
  2485. if (isset($sortParams['GET'])) {
  2486. $getargs = $sortParams['GET'];
  2487. if (is_array($getargs)) {
  2488. foreach ($getargs as $getarg) {
  2489. $query[] = 'GET';
  2490. $query[] = $getarg;
  2491. }
  2492. }
  2493. else {
  2494. $query[] = 'GET';
  2495. $query[] = $getargs;
  2496. }
  2497. }
  2498. if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
  2499. && count($sortParams['LIMIT']) == 2) {
  2500. $query[] = 'LIMIT';
  2501. $query[] = $sortParams['LIMIT'][0];
  2502. $query[] = $sortParams['LIMIT'][1];
  2503. }
  2504. if (isset($sortParams['SORT'])) {
  2505. $query[] = strtoupper($sortParams['SORT']);
  2506. }
  2507. if (isset($sortParams['ALPHA']) && $sortParams['ALPHA'] == true) {
  2508. $query[] = 'ALPHA';
  2509. }
  2510. if (isset($sortParams['STORE'])) {
  2511. $query[] = 'STORE';
  2512. $query[] = $sortParams['STORE'];
  2513. }
  2514. return $query;
  2515. }
  2516. }
  2517. /* transactions */
  2518. class Predis_Commands_Multi extends Predis_MultiBulkCommand {
  2519. public function canBeHashed() { return false; }
  2520. public function getCommandId() { return 'MULTI'; }
  2521. }
  2522. class Predis_Commands_Exec extends Predis_MultiBulkCommand {
  2523. public function canBeHashed() { return false; }
  2524. public function getCommandId() { return 'EXEC'; }
  2525. }
  2526. class Predis_Commands_Discard extends Predis_MultiBulkCommand {
  2527. public function canBeHashed() { return false; }
  2528. public function getCommandId() { return 'DISCARD'; }
  2529. }
  2530. /* publish/subscribe */
  2531. class Predis_Commands_Subscribe extends Predis_MultiBulkCommand {
  2532. public function canBeHashed() { return false; }
  2533. public function getCommandId() { return 'SUBSCRIBE'; }
  2534. }
  2535. class Predis_Commands_Unsubscribe extends Predis_MultiBulkCommand {
  2536. public function canBeHashed() { return false; }
  2537. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2538. }
  2539. class Predis_Commands_SubscribeByPattern extends Predis_MultiBulkCommand {
  2540. public function canBeHashed() { return false; }
  2541. public function getCommandId() { return 'PSUBSCRIBE'; }
  2542. }
  2543. class Predis_Commands_UnsubscribeByPattern extends Predis_MultiBulkCommand {
  2544. public function canBeHashed() { return false; }
  2545. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  2546. }
  2547. class Predis_Commands_Publish extends Predis_MultiBulkCommand {
  2548. public function canBeHashed() { return false; }
  2549. public function getCommandId() { return 'PUBLISH'; }
  2550. }
  2551. class Predis_Commands_Watch extends Predis_MultiBulkCommand {
  2552. public function canBeHashed() { return false; }
  2553. public function getCommandId() { return 'WATCH'; }
  2554. public function filterArguments(Array $arguments) {
  2555. if (isset($arguments[0]) && is_array($arguments[0])) {
  2556. return $arguments[0];
  2557. }
  2558. return $arguments;
  2559. }
  2560. public function parseResponse($data) { return (bool) $data; }
  2561. }
  2562. class Predis_Commands_Unwatch extends Predis_MultiBulkCommand {
  2563. public function canBeHashed() { return false; }
  2564. public function getCommandId() { return 'UNWATCH'; }
  2565. public function parseResponse($data) { return (bool) $data; }
  2566. }
  2567. /* persistence control commands */
  2568. class Predis_Commands_Save extends Predis_MultiBulkCommand {
  2569. public function canBeHashed() { return false; }
  2570. public function getCommandId() { return 'SAVE'; }
  2571. }
  2572. class Predis_Commands_BackgroundSave extends Predis_MultiBulkCommand {
  2573. public function canBeHashed() { return false; }
  2574. public function getCommandId() { return 'BGSAVE'; }
  2575. public function parseResponse($data) {
  2576. if ($data == 'Background saving started') {
  2577. return true;
  2578. }
  2579. return $data;
  2580. }
  2581. }
  2582. class Predis_Commands_BackgroundRewriteAppendOnlyFile extends Predis_MultiBulkCommand {
  2583. public function canBeHashed() { return false; }
  2584. public function getCommandId() { return 'BGREWRITEAOF'; }
  2585. public function parseResponse($data) {
  2586. return $data == 'Background append only file rewriting started';
  2587. }
  2588. }
  2589. class Predis_Commands_LastSave extends Predis_MultiBulkCommand {
  2590. public function canBeHashed() { return false; }
  2591. public function getCommandId() { return 'LASTSAVE'; }
  2592. }
  2593. class Predis_Commands_Shutdown extends Predis_MultiBulkCommand {
  2594. public function canBeHashed() { return false; }
  2595. public function getCommandId() { return 'SHUTDOWN'; }
  2596. public function closesConnection() { return true; }
  2597. }
  2598. /* remote server control commands */
  2599. class Predis_Commands_Info extends Predis_MultiBulkCommand {
  2600. public function canBeHashed() { return false; }
  2601. public function getCommandId() { return 'INFO'; }
  2602. public function parseResponse($data) {
  2603. $info = array();
  2604. $infoLines = explode("\r\n", $data, -1);
  2605. foreach ($infoLines as $row) {
  2606. list($k, $v) = explode(':', $row);
  2607. if (!preg_match('/^db\d+$/', $k)) {
  2608. $info[$k] = $v;
  2609. }
  2610. else {
  2611. $db = array();
  2612. foreach (explode(',', $v) as $dbvar) {
  2613. list($dbvk, $dbvv) = explode('=', $dbvar);
  2614. $db[trim($dbvk)] = $dbvv;
  2615. }
  2616. $info[$k] = $db;
  2617. }
  2618. }
  2619. return $info;
  2620. }
  2621. }
  2622. class Predis_Commands_SlaveOf extends Predis_MultiBulkCommand {
  2623. public function canBeHashed() { return false; }
  2624. public function getCommandId() { return 'SLAVEOF'; }
  2625. public function filterArguments(Array $arguments) {
  2626. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2627. return array('NO', 'ONE');
  2628. }
  2629. return $arguments;
  2630. }
  2631. }
  2632. class Predis_Commands_Config extends Predis_MultiBulkCommand {
  2633. public function canBeHashed() { return false; }
  2634. public function getCommandId() { return 'CONFIG'; }
  2635. }
  2636. ?>