Predis.php 124 KB

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