Predis.php 107 KB

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