Predis.php 110 KB

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