Predis.php 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202
  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. if (is_array($this->_options[$subscribeAction])) {
  941. foreach ($this->_options[$subscribeAction] as $subscription) {
  942. $this->$subscribeAction($subscription);
  943. }
  944. }
  945. else {
  946. $this->$subscribeAction($this->_options[$subscribeAction]);
  947. }
  948. }
  949. }
  950. private function isFlagSet($value) {
  951. return ($this->_statusFlags & $value) === $value;
  952. }
  953. public function subscribe(/* arguments */) {
  954. $this->writeCommand(self::SUBSCRIBE, func_get_args());
  955. $this->_statusFlags |= self::STATUS_SUBSCRIBED;
  956. }
  957. public function unsubscribe(/* arguments */) {
  958. $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
  959. }
  960. public function psubscribe(/* arguments */) {
  961. $this->writeCommand(self::PSUBSCRIBE, func_get_args());
  962. $this->_statusFlags |= self::STATUS_PSUBSCRIBED;
  963. }
  964. public function punsubscribe(/* arguments */) {
  965. $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
  966. }
  967. public function closeContext() {
  968. if ($this->valid()) {
  969. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  970. $this->unsubscribe();
  971. }
  972. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  973. $this->punsubscribe();
  974. }
  975. }
  976. }
  977. private function writeCommand($method, $arguments) {
  978. if (count($arguments) === 1 && is_array($arguments[0])) {
  979. $arguments = $arguments[0];
  980. }
  981. $command = $this->_redisClient->createCommand($method, $arguments);
  982. $this->_redisClient->getConnection()->writeCommand($command);
  983. }
  984. public function rewind() {
  985. // NOOP
  986. }
  987. public function current() {
  988. return $this->getValue();
  989. }
  990. public function key() {
  991. return $this->_position;
  992. }
  993. public function next() {
  994. if ($this->isFlagSet(self::STATUS_VALID)) {
  995. $this->_position++;
  996. }
  997. return $this->_position;
  998. }
  999. public function valid() {
  1000. $subscriptions = self::STATUS_SUBSCRIBED + self::STATUS_PSUBSCRIBED;
  1001. return $this->isFlagSet(self::STATUS_VALID)
  1002. && ($this->_statusFlags & $subscriptions) > 0;
  1003. }
  1004. private function invalidate() {
  1005. $this->_statusFlags = 0x0000;
  1006. }
  1007. private function getValue() {
  1008. $reader = $this->_redisClient->getResponseReader();
  1009. $connection = $this->_redisClient->getConnection();
  1010. $response = $reader->read($connection);
  1011. switch ($response[0]) {
  1012. case self::SUBSCRIBE:
  1013. case self::UNSUBSCRIBE:
  1014. case self::PSUBSCRIBE:
  1015. case self::PUNSUBSCRIBE:
  1016. if ($response[2] === 0) {
  1017. $this->invalidate();
  1018. }
  1019. case self::MESSAGE:
  1020. return (object) array(
  1021. 'kind' => $response[0],
  1022. 'channel' => $response[1],
  1023. 'payload' => $response[2],
  1024. );
  1025. case self::PMESSAGE:
  1026. return (object) array(
  1027. 'kind' => $response[0],
  1028. 'pattern' => $response[1],
  1029. 'channel' => $response[2],
  1030. 'payload' => $response[3],
  1031. );
  1032. default:
  1033. throw new \Predis\ClientException(
  1034. "Received an unknown message type {$response[0]} inside of a pubsub context"
  1035. );
  1036. }
  1037. }
  1038. }
  1039. /* ------------------------------------------------------------------------- */
  1040. class ConnectionParameters {
  1041. const DEFAULT_SCHEME = 'redis';
  1042. const DEFAULT_HOST = '127.0.0.1';
  1043. const DEFAULT_PORT = 6379;
  1044. const DEFAULT_TIMEOUT = 5;
  1045. private $_parameters;
  1046. public function __construct($parameters = null) {
  1047. $parameters = $parameters ?: array();
  1048. $this->_parameters = is_array($parameters)
  1049. ? self::filterConnectionParams($parameters)
  1050. : self::parseURI($parameters);
  1051. }
  1052. private static function parseURI($uri) {
  1053. if (stripos($uri, 'unix') === 0) {
  1054. // Hack to support URIs for UNIX sockets with minimal effort.
  1055. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
  1056. }
  1057. $parsed = @parse_url($uri);
  1058. if ($parsed == false) {
  1059. throw new ClientException("Invalid URI: $uri");
  1060. }
  1061. if (array_key_exists('query', $parsed)) {
  1062. $details = array();
  1063. foreach (explode('&', $parsed['query']) as $kv) {
  1064. list($k, $v) = explode('=', $kv);
  1065. switch ($k) {
  1066. case 'database':
  1067. $details['database'] = $v;
  1068. break;
  1069. case 'password':
  1070. $details['password'] = $v;
  1071. break;
  1072. case 'connection_async':
  1073. $details['connection_async'] = $v;
  1074. break;
  1075. case 'connection_persistent':
  1076. $details['connection_persistent'] = $v;
  1077. break;
  1078. case 'connection_timeout':
  1079. $details['connection_timeout'] = $v;
  1080. break;
  1081. case 'read_write_timeout':
  1082. $details['read_write_timeout'] = $v;
  1083. break;
  1084. case 'alias':
  1085. $details['alias'] = $v;
  1086. break;
  1087. case 'weight':
  1088. $details['weight'] = $v;
  1089. break;
  1090. case 'path':
  1091. $details['path'] = $v;
  1092. break;
  1093. }
  1094. }
  1095. $parsed = array_merge($parsed, $details);
  1096. }
  1097. return self::filterConnectionParams($parsed);
  1098. }
  1099. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  1100. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  1101. }
  1102. private static function filterConnectionParams($parameters) {
  1103. return array(
  1104. 'scheme' => self::getParamOrDefault($parameters, 'scheme', self::DEFAULT_SCHEME),
  1105. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  1106. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  1107. 'database' => self::getParamOrDefault($parameters, 'database'),
  1108. 'password' => self::getParamOrDefault($parameters, 'password'),
  1109. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  1110. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  1111. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  1112. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  1113. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  1114. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  1115. 'path' => self::getParamOrDefault($parameters, 'path'),
  1116. );
  1117. }
  1118. public function __get($parameter) {
  1119. return $this->_parameters[$parameter];
  1120. }
  1121. public function __isset($parameter) {
  1122. return isset($this->_parameters[$parameter]);
  1123. }
  1124. }
  1125. interface IConnection {
  1126. public function connect();
  1127. public function disconnect();
  1128. public function isConnected();
  1129. public function writeCommand(Command $command);
  1130. public function readResponse(Command $command);
  1131. public function executeCommand(Command $command);
  1132. }
  1133. class Connection implements IConnection {
  1134. private $_params, $_socket, $_initCmds, $_reader, $_initializer;
  1135. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  1136. $scheme = $parameters->scheme;
  1137. if ($scheme !== 'redis' && $scheme !== 'tcp' && $scheme !== 'unix') {
  1138. throw new \InvalidArgumentException("Invalid scheme: $scheme");
  1139. }
  1140. $this->_initializer = array($this, "{$parameters->scheme}StreamInitializer");
  1141. $this->_params = $parameters;
  1142. $this->_initCmds = array();
  1143. $this->_reader = $reader ?: new ResponseReader();
  1144. }
  1145. public function __destruct() {
  1146. if (!$this->_params->connection_persistent) {
  1147. $this->disconnect();
  1148. }
  1149. }
  1150. public function isConnected() {
  1151. return isset($this->_socket);
  1152. }
  1153. public function connect() {
  1154. if ($this->isConnected()) {
  1155. throw new ClientException('Connection already estabilished');
  1156. }
  1157. $this->_socket = call_user_func($this->_initializer, $this->_params);
  1158. if (count($this->_initCmds) > 0){
  1159. $this->sendInitializationCommands();
  1160. }
  1161. }
  1162. private function tcpStreamInitializer(ConnectionParameters $parameters) {
  1163. return $this->redisStreamInitializer($parameters);
  1164. }
  1165. private function redisStreamInitializer(ConnectionParameters $parameters) {
  1166. $uri = sprintf('tcp://%s:%d/', $parameters->host, $parameters->port);
  1167. $connectFlags = STREAM_CLIENT_CONNECT;
  1168. if ($parameters->connection_async) {
  1169. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  1170. }
  1171. if ($parameters->connection_persistent) {
  1172. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1173. }
  1174. $socket = @stream_socket_client(
  1175. $uri, $errno, $errstr, $parameters->connection_timeout, $connectFlags
  1176. );
  1177. if (!$socket) {
  1178. $this->onCommunicationException(trim($errstr), $errno);
  1179. }
  1180. if (isset($parameters->read_write_timeout)) {
  1181. $rwtimeout = $parameters->read_write_timeout;
  1182. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  1183. $timeoutSeconds = floor($parameters->read_write_timeout);
  1184. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  1185. stream_set_timeout($socket, $rwtimeout, $timeoutUSeconds);
  1186. }
  1187. return $socket;
  1188. }
  1189. private function unixStreamInitializer(ConnectionParameters $parameters) {
  1190. $uri = sprintf('unix:///%s', $parameters->path);
  1191. $connectFlags = STREAM_CLIENT_CONNECT;
  1192. if ($parameters->connection_persistent) {
  1193. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1194. }
  1195. $socket = @stream_socket_client(
  1196. $uri, $errno, $errstr, $parameters->connection_timeout, $connectFlags
  1197. );
  1198. if (!$socket) {
  1199. $this->onCommunicationException(trim($errstr), $errno);
  1200. }
  1201. return $socket;
  1202. }
  1203. public function disconnect() {
  1204. if ($this->isConnected()) {
  1205. fclose($this->_socket);
  1206. unset($this->_socket);
  1207. }
  1208. }
  1209. public function pushInitCommand(Command $command){
  1210. $this->_initCmds[] = $command;
  1211. }
  1212. private function sendInitializationCommands() {
  1213. foreach ($this->_initCmds as $command) {
  1214. $this->writeCommand($command);
  1215. }
  1216. foreach ($this->_initCmds as $command) {
  1217. $this->readResponse($command);
  1218. }
  1219. }
  1220. private function onCommunicationException($message, $code = null) {
  1221. Shared\Utils::onCommunicationException(
  1222. new CommunicationException($this, $message, $code)
  1223. );
  1224. }
  1225. public function writeCommand(Command $command) {
  1226. $this->writeBytes($command());
  1227. }
  1228. public function readResponse(Command $command) {
  1229. $response = $this->_reader->read($this);
  1230. return isset($response->skipParse) ? $response : $command->parseResponse($response);
  1231. }
  1232. public function executeCommand(Command $command) {
  1233. $this->writeCommand($command);
  1234. if ($command->closesConnection()) {
  1235. return $this->disconnect();
  1236. }
  1237. return $this->readResponse($command);
  1238. }
  1239. public function rawCommand($rawCommandData, $closesConnection = false) {
  1240. $this->writeBytes($rawCommandData);
  1241. if ($closesConnection) {
  1242. $this->disconnect();
  1243. return;
  1244. }
  1245. return $this->_reader->read($this);
  1246. }
  1247. public function writeBytes($value) {
  1248. $socket = $this->getSocket();
  1249. while (($length = strlen($value)) > 0) {
  1250. $written = fwrite($socket, $value);
  1251. if ($length === $written) {
  1252. return true;
  1253. }
  1254. if ($written === false || $written === 0) {
  1255. $this->onCommunicationException('Error while writing bytes to the server');
  1256. }
  1257. $value = substr($value, $written);
  1258. }
  1259. return true;
  1260. }
  1261. public function readBytes($length) {
  1262. if ($length <= 0) {
  1263. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  1264. }
  1265. $socket = $this->getSocket();
  1266. $value = '';
  1267. do {
  1268. $chunk = fread($socket, $length);
  1269. if ($chunk === false || $chunk === '') {
  1270. $this->onCommunicationException('Error while reading bytes from the server');
  1271. }
  1272. $value .= $chunk;
  1273. }
  1274. while (($length -= strlen($chunk)) > 0);
  1275. return $value;
  1276. }
  1277. public function readLine() {
  1278. $socket = $this->getSocket();
  1279. $value = '';
  1280. do {
  1281. $chunk = fgets($socket);
  1282. if ($chunk === false || $chunk === '') {
  1283. $this->onCommunicationException('Error while reading line from the server');
  1284. }
  1285. $value .= $chunk;
  1286. }
  1287. while (substr($value, -2) !== "\r\n");
  1288. return substr($value, 0, -2);
  1289. }
  1290. public function getSocket() {
  1291. if (isset($this->_socket)) {
  1292. return $this->_socket;
  1293. }
  1294. $this->connect();
  1295. return $this->_socket;
  1296. }
  1297. public function getResponseReader() {
  1298. return $this->_reader;
  1299. }
  1300. public function getParameters() {
  1301. return $this->_params;
  1302. }
  1303. public function __toString() {
  1304. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  1305. }
  1306. }
  1307. class ConnectionCluster implements IConnection, \IteratorAggregate {
  1308. private $_pool, $_distributor;
  1309. public function __construct(Distribution\IDistributionStrategy $distributor = null) {
  1310. $this->_pool = array();
  1311. $this->_distributor = $distributor ?: new Distribution\HashRing();
  1312. }
  1313. public function isConnected() {
  1314. foreach ($this->_pool as $connection) {
  1315. if ($connection->isConnected()) {
  1316. return true;
  1317. }
  1318. }
  1319. return false;
  1320. }
  1321. public function connect() {
  1322. foreach ($this->_pool as $connection) {
  1323. $connection->connect();
  1324. }
  1325. }
  1326. public function disconnect() {
  1327. foreach ($this->_pool as $connection) {
  1328. $connection->disconnect();
  1329. }
  1330. }
  1331. public function add(Connection $connection) {
  1332. $parameters = $connection->getParameters();
  1333. if (isset($parameters->alias)) {
  1334. $this->_pool[$parameters->alias] = $connection;
  1335. }
  1336. else {
  1337. $this->_pool[] = $connection;
  1338. }
  1339. $this->_distributor->add($connection, $parameters->weight);
  1340. }
  1341. public function getConnection(Command $command) {
  1342. if ($command->canBeHashed() === false) {
  1343. throw new ClientException(
  1344. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1345. );
  1346. }
  1347. return $this->_distributor->get($command->getHash($this->_distributor));
  1348. }
  1349. public function getConnectionById($id = null) {
  1350. $alias = $id ?: 0;
  1351. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1352. }
  1353. public function getIterator() {
  1354. return new \ArrayIterator($this->_pool);
  1355. }
  1356. public function writeCommand(Command $command) {
  1357. $this->getConnection($command)->writeCommand($command);
  1358. }
  1359. public function readResponse(Command $command) {
  1360. return $this->getConnection($command)->readResponse($command);
  1361. }
  1362. public function executeCommand(Command $command) {
  1363. $connection = $this->getConnection($command);
  1364. $connection->writeCommand($command);
  1365. return $connection->readResponse($command);
  1366. }
  1367. }
  1368. /* ------------------------------------------------------------------------- */
  1369. abstract class RedisServerProfile {
  1370. private static $_serverProfiles;
  1371. private $_registeredCommands;
  1372. public function __construct() {
  1373. $this->_registeredCommands = $this->getSupportedCommands();
  1374. }
  1375. public abstract function getVersion();
  1376. protected abstract function getSupportedCommands();
  1377. public static function getDefault() {
  1378. return self::get('default');
  1379. }
  1380. public static function getDevelopment() {
  1381. return self::get('dev');
  1382. }
  1383. private static function predisServerProfiles() {
  1384. return array(
  1385. '1.2' => '\Predis\RedisServer_v1_2',
  1386. '2.0' => '\Predis\RedisServer_v2_0',
  1387. '2.2' => '\Predis\RedisServer_v2_2',
  1388. 'default' => '\Predis\RedisServer_v2_0',
  1389. 'dev' => '\Predis\RedisServer_vNext',
  1390. );
  1391. }
  1392. public static function registerProfile($profileClass, $aliases) {
  1393. if (!isset(self::$_serverProfiles)) {
  1394. self::$_serverProfiles = self::predisServerProfiles();
  1395. }
  1396. $profileReflection = new \ReflectionClass($profileClass);
  1397. if (!$profileReflection->isSubclassOf('\Predis\RedisServerProfile')) {
  1398. throw new ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1399. }
  1400. if (is_array($aliases)) {
  1401. foreach ($aliases as $alias) {
  1402. self::$_serverProfiles[$alias] = $profileClass;
  1403. }
  1404. }
  1405. else {
  1406. self::$_serverProfiles[$aliases] = $profileClass;
  1407. }
  1408. }
  1409. public static function get($version) {
  1410. if (!isset(self::$_serverProfiles)) {
  1411. self::$_serverProfiles = self::predisServerProfiles();
  1412. }
  1413. if (!isset(self::$_serverProfiles[$version])) {
  1414. throw new ClientException("Unknown server profile: $version");
  1415. }
  1416. $profile = self::$_serverProfiles[$version];
  1417. return new $profile();
  1418. }
  1419. public function supportsCommands(Array $commands) {
  1420. foreach ($commands as $command) {
  1421. if ($this->supportsCommand($command) === false) {
  1422. return false;
  1423. }
  1424. }
  1425. return true;
  1426. }
  1427. public function supportsCommand($command) {
  1428. return isset($this->_registeredCommands[$command]);
  1429. }
  1430. public function createCommand($method, $arguments = array()) {
  1431. if (!isset($this->_registeredCommands[$method])) {
  1432. throw new ClientException("'$method' is not a registered Redis command");
  1433. }
  1434. $commandClass = $this->_registeredCommands[$method];
  1435. $command = new $commandClass();
  1436. $command->setArgumentsArray($arguments);
  1437. return $command;
  1438. }
  1439. public function registerCommands(Array $commands) {
  1440. foreach ($commands as $command => $aliases) {
  1441. $this->registerCommand($command, $aliases);
  1442. }
  1443. }
  1444. public function registerCommand($command, $aliases) {
  1445. $commandReflection = new \ReflectionClass($command);
  1446. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  1447. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1448. }
  1449. if (is_array($aliases)) {
  1450. foreach ($aliases as $alias) {
  1451. $this->_registeredCommands[$alias] = $command;
  1452. }
  1453. }
  1454. else {
  1455. $this->_registeredCommands[$aliases] = $command;
  1456. }
  1457. }
  1458. public function __toString() {
  1459. return $this->getVersion();
  1460. }
  1461. }
  1462. class RedisServer_v1_2 extends RedisServerProfile {
  1463. public function getVersion() { return '1.2'; }
  1464. public function getSupportedCommands() {
  1465. return array(
  1466. /* miscellaneous commands */
  1467. 'ping' => '\Predis\Commands\Ping',
  1468. 'echo' => '\Predis\Commands\DoEcho',
  1469. 'auth' => '\Predis\Commands\Auth',
  1470. /* connection handling */
  1471. 'quit' => '\Predis\Commands\Quit',
  1472. /* commands operating on string values */
  1473. 'set' => '\Predis\Commands\Set',
  1474. 'setnx' => '\Predis\Commands\SetPreserve',
  1475. 'setPreserve' => '\Predis\Commands\SetPreserve',
  1476. 'mset' => '\Predis\Commands\SetMultiple',
  1477. 'setMultiple' => '\Predis\Commands\SetMultiple',
  1478. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1479. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  1480. 'get' => '\Predis\Commands\Get',
  1481. 'mget' => '\Predis\Commands\GetMultiple',
  1482. 'getMultiple' => '\Predis\Commands\GetMultiple',
  1483. 'getset' => '\Predis\Commands\GetSet',
  1484. 'getSet' => '\Predis\Commands\GetSet',
  1485. 'incr' => '\Predis\Commands\Increment',
  1486. 'increment' => '\Predis\Commands\Increment',
  1487. 'incrby' => '\Predis\Commands\IncrementBy',
  1488. 'incrementBy' => '\Predis\Commands\IncrementBy',
  1489. 'decr' => '\Predis\Commands\Decrement',
  1490. 'decrement' => '\Predis\Commands\Decrement',
  1491. 'decrby' => '\Predis\Commands\DecrementBy',
  1492. 'decrementBy' => '\Predis\Commands\DecrementBy',
  1493. 'exists' => '\Predis\Commands\Exists',
  1494. 'del' => '\Predis\Commands\Delete',
  1495. 'delete' => '\Predis\Commands\Delete',
  1496. 'type' => '\Predis\Commands\Type',
  1497. /* commands operating on the key space */
  1498. 'keys' => '\Predis\Commands\Keys_v1_2',
  1499. 'randomkey' => '\Predis\Commands\RandomKey',
  1500. 'randomKey' => '\Predis\Commands\RandomKey',
  1501. 'rename' => '\Predis\Commands\Rename',
  1502. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1503. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  1504. 'expire' => '\Predis\Commands\Expire',
  1505. 'expireat' => '\Predis\Commands\ExpireAt',
  1506. 'expireAt' => '\Predis\Commands\ExpireAt',
  1507. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1508. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  1509. 'ttl' => '\Predis\Commands\TimeToLive',
  1510. 'timeToLive' => '\Predis\Commands\TimeToLive',
  1511. /* commands operating on lists */
  1512. 'rpush' => '\Predis\Commands\ListPushTail',
  1513. 'pushTail' => '\Predis\Commands\ListPushTail',
  1514. 'lpush' => '\Predis\Commands\ListPushHead',
  1515. 'pushHead' => '\Predis\Commands\ListPushHead',
  1516. 'llen' => '\Predis\Commands\ListLength',
  1517. 'listLength' => '\Predis\Commands\ListLength',
  1518. 'lrange' => '\Predis\Commands\ListRange',
  1519. 'listRange' => '\Predis\Commands\ListRange',
  1520. 'ltrim' => '\Predis\Commands\ListTrim',
  1521. 'listTrim' => '\Predis\Commands\ListTrim',
  1522. 'lindex' => '\Predis\Commands\ListIndex',
  1523. 'listIndex' => '\Predis\Commands\ListIndex',
  1524. 'lset' => '\Predis\Commands\ListSet',
  1525. 'listSet' => '\Predis\Commands\ListSet',
  1526. 'lrem' => '\Predis\Commands\ListRemove',
  1527. 'listRemove' => '\Predis\Commands\ListRemove',
  1528. 'lpop' => '\Predis\Commands\ListPopFirst',
  1529. 'popFirst' => '\Predis\Commands\ListPopFirst',
  1530. 'rpop' => '\Predis\Commands\ListPopLast',
  1531. 'popLast' => '\Predis\Commands\ListPopLast',
  1532. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1533. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  1534. /* commands operating on sets */
  1535. 'sadd' => '\Predis\Commands\SetAdd',
  1536. 'setAdd' => '\Predis\Commands\SetAdd',
  1537. 'srem' => '\Predis\Commands\SetRemove',
  1538. 'setRemove' => '\Predis\Commands\SetRemove',
  1539. 'spop' => '\Predis\Commands\SetPop',
  1540. 'setPop' => '\Predis\Commands\SetPop',
  1541. 'smove' => '\Predis\Commands\SetMove',
  1542. 'setMove' => '\Predis\Commands\SetMove',
  1543. 'scard' => '\Predis\Commands\SetCardinality',
  1544. 'setCardinality' => '\Predis\Commands\SetCardinality',
  1545. 'sismember' => '\Predis\Commands\SetIsMember',
  1546. 'setIsMember' => '\Predis\Commands\SetIsMember',
  1547. 'sinter' => '\Predis\Commands\SetIntersection',
  1548. 'setIntersection' => '\Predis\Commands\SetIntersection',
  1549. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1550. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  1551. 'sunion' => '\Predis\Commands\SetUnion',
  1552. 'setUnion' => '\Predis\Commands\SetUnion',
  1553. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1554. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  1555. 'sdiff' => '\Predis\Commands\SetDifference',
  1556. 'setDifference' => '\Predis\Commands\SetDifference',
  1557. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1558. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  1559. 'smembers' => '\Predis\Commands\SetMembers',
  1560. 'setMembers' => '\Predis\Commands\SetMembers',
  1561. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1562. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  1563. /* commands operating on sorted sets */
  1564. 'zadd' => '\Predis\Commands\ZSetAdd',
  1565. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  1566. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1567. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  1568. 'zrem' => '\Predis\Commands\ZSetRemove',
  1569. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  1570. 'zrange' => '\Predis\Commands\ZSetRange',
  1571. 'zsetRange' => '\Predis\Commands\ZSetRange',
  1572. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1573. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1574. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1575. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1576. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1577. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1578. 'zscore' => '\Predis\Commands\ZSetScore',
  1579. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1580. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1581. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1582. /* multiple databases handling commands */
  1583. 'select' => '\Predis\Commands\SelectDatabase',
  1584. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  1585. 'move' => '\Predis\Commands\MoveKey',
  1586. 'moveKey' => '\Predis\Commands\MoveKey',
  1587. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1588. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  1589. 'flushall' => '\Predis\Commands\FlushAll',
  1590. 'flushDatabases' => '\Predis\Commands\FlushAll',
  1591. /* sorting */
  1592. 'sort' => '\Predis\Commands\Sort',
  1593. /* remote server control commands */
  1594. 'info' => '\Predis\Commands\Info',
  1595. 'slaveof' => '\Predis\Commands\SlaveOf',
  1596. 'slaveOf' => '\Predis\Commands\SlaveOf',
  1597. /* persistence control commands */
  1598. 'save' => '\Predis\Commands\Save',
  1599. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1600. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  1601. 'lastsave' => '\Predis\Commands\LastSave',
  1602. 'lastSave' => '\Predis\Commands\LastSave',
  1603. 'shutdown' => '\Predis\Commands\Shutdown',
  1604. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1605. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1606. );
  1607. }
  1608. }
  1609. class RedisServer_v2_0 extends RedisServer_v1_2 {
  1610. public function getVersion() { return '2.0'; }
  1611. public function getSupportedCommands() {
  1612. return array_merge(parent::getSupportedCommands(), array(
  1613. /* transactions */
  1614. 'multi' => '\Predis\Commands\Multi',
  1615. 'exec' => '\Predis\Commands\Exec',
  1616. 'discard' => '\Predis\Commands\Discard',
  1617. /* commands operating on string values */
  1618. 'setex' => '\Predis\Commands\SetExpire',
  1619. 'setExpire' => '\Predis\Commands\SetExpire',
  1620. 'append' => '\Predis\Commands\Append',
  1621. 'substr' => '\Predis\Commands\Substr',
  1622. /* commands operating on the key space */
  1623. 'keys' => '\Predis\Commands\Keys',
  1624. /* commands operating on lists */
  1625. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1626. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1627. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1628. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1629. /* commands operating on sorted sets */
  1630. 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
  1631. 'zsetUnionStore' => '\Predis\Commands\ZSetUnionStore',
  1632. 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
  1633. 'zsetIntersectionStore' => '\Predis\Commands\ZSetIntersectionStore',
  1634. 'zcount' => '\Predis\Commands\ZSetCount',
  1635. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1636. 'zrank' => '\Predis\Commands\ZSetRank',
  1637. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1638. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1639. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1640. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1641. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1642. /* commands operating on hashes */
  1643. 'hset' => '\Predis\Commands\HashSet',
  1644. 'hashSet' => '\Predis\Commands\HashSet',
  1645. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1646. 'hashSetPreserve' => '\Predis\Commands\HashSetPreserve',
  1647. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1648. 'hashSetMultiple' => '\Predis\Commands\HashSetMultiple',
  1649. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1650. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1651. 'hget' => '\Predis\Commands\HashGet',
  1652. 'hashGet' => '\Predis\Commands\HashGet',
  1653. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1654. 'hashGetMultiple' => '\Predis\Commands\HashGetMultiple',
  1655. 'hdel' => '\Predis\Commands\HashDelete',
  1656. 'hashDelete' => '\Predis\Commands\HashDelete',
  1657. 'hexists' => '\Predis\Commands\HashExists',
  1658. 'hashExists' => '\Predis\Commands\HashExists',
  1659. 'hlen' => '\Predis\Commands\HashLength',
  1660. 'hashLength' => '\Predis\Commands\HashLength',
  1661. 'hkeys' => '\Predis\Commands\HashKeys',
  1662. 'hashKeys' => '\Predis\Commands\HashKeys',
  1663. 'hvals' => '\Predis\Commands\HashValues',
  1664. 'hashValues' => '\Predis\Commands\HashValues',
  1665. 'hgetall' => '\Predis\Commands\HashGetAll',
  1666. 'hashGetAll' => '\Predis\Commands\HashGetAll',
  1667. /* publish - subscribe */
  1668. 'subscribe' => '\Predis\Commands\Subscribe',
  1669. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1670. 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
  1671. 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
  1672. 'publish' => '\Predis\Commands\Publish',
  1673. /* remote server control commands */
  1674. 'config' => '\Predis\Commands\Config',
  1675. 'configuration' => '\Predis\Commands\Config',
  1676. ));
  1677. }
  1678. }
  1679. class RedisServer_v2_2 extends RedisServer_v2_0 {
  1680. public function getVersion() { return '2.2'; }
  1681. public function getSupportedCommands() {
  1682. return array_merge(parent::getSupportedCommands(), array(
  1683. /* transactions */
  1684. 'watch' => '\Predis\Commands\Watch',
  1685. 'unwatch' => '\Predis\Commands\Unwatch',
  1686. /* commands operating on string values */
  1687. 'strlen' => '\Predis\Commands\Strlen',
  1688. 'setrange' => '\Predis\Commands\SetRange',
  1689. 'getrange' => '\Predis\Commands\Substr',
  1690. 'setbit' => '\Predis\Commands\SetBit',
  1691. 'getbit' => '\Predis\Commands\GetBit',
  1692. /* commands operating on the key space */
  1693. 'persist' => '\Predis\Commands\Persist',
  1694. /* commands operating on lists */
  1695. 'rpushx' => '\Predis\Commands\ListPushTailX',
  1696. 'lpushx' => '\Predis\Commands\ListPushHeadX',
  1697. 'linsert' => '\Predis\Commands\ListInsert',
  1698. 'brpoplpush' => '\Predis\Commands\ListPopLastPushHeadBlocking',
  1699. /* commands operating on sorted sets */
  1700. 'zrevrangebyscore' => '\Predis\Commands\ZSetReverseRangeByScore',
  1701. ));
  1702. }
  1703. }
  1704. class RedisServer_vNext extends RedisServer_v2_2 {
  1705. public function getVersion() { return 'DEV'; }
  1706. public function getSupportedCommands() {
  1707. return array_merge(parent::getSupportedCommands(), array(
  1708. /* remote server control commands */
  1709. 'info' => '\Predis\Commands\Info_v24',
  1710. ));
  1711. }
  1712. }
  1713. /* ------------------------------------------------------------------------- */
  1714. namespace Predis\Pipeline;
  1715. interface IPipelineExecutor {
  1716. public function execute(\Predis\IConnection $connection, &$commands);
  1717. }
  1718. class StandardExecutor implements IPipelineExecutor {
  1719. public function execute(\Predis\IConnection $connection, &$commands) {
  1720. $sizeofPipe = count($commands);
  1721. $values = array();
  1722. foreach ($commands as $command) {
  1723. $connection->writeCommand($command);
  1724. }
  1725. try {
  1726. for ($i = 0; $i < $sizeofPipe; $i++) {
  1727. $response = $connection->readResponse($commands[$i]);
  1728. $values[] = $response instanceof \Iterator
  1729. ? iterator_to_array($response)
  1730. : $response;
  1731. unset($commands[$i]);
  1732. }
  1733. }
  1734. catch (\Predis\ServerException $exception) {
  1735. // force disconnection to prevent protocol desynchronization
  1736. $connection->disconnect();
  1737. throw $exception;
  1738. }
  1739. return $values;
  1740. }
  1741. }
  1742. class SafeExecutor implements IPipelineExecutor {
  1743. public function execute(\Predis\IConnection $connection, &$commands) {
  1744. $sizeofPipe = count($commands);
  1745. $values = array();
  1746. foreach ($commands as $command) {
  1747. try {
  1748. $connection->writeCommand($command);
  1749. }
  1750. catch (\Predis\CommunicationException $exception) {
  1751. return array_fill(0, $sizeofPipe, $exception);
  1752. }
  1753. }
  1754. for ($i = 0; $i < $sizeofPipe; $i++) {
  1755. $command = $commands[$i];
  1756. unset($commands[$i]);
  1757. try {
  1758. $response = $connection->readResponse($command);
  1759. $values[] = ($response instanceof \Iterator
  1760. ? iterator_to_array($response)
  1761. : $response
  1762. );
  1763. }
  1764. catch (\Predis\ServerException $exception) {
  1765. $values[] = $exception->toResponseError();
  1766. }
  1767. catch (\Predis\CommunicationException $exception) {
  1768. $toAdd = count($commands) - count($values);
  1769. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  1770. break;
  1771. }
  1772. }
  1773. return $values;
  1774. }
  1775. }
  1776. class SafeClusterExecutor implements IPipelineExecutor {
  1777. public function execute(\Predis\IConnection $connection, &$commands) {
  1778. $connectionExceptions = array();
  1779. $sizeofPipe = count($commands);
  1780. $values = array();
  1781. foreach ($commands as $command) {
  1782. $cmdConnection = $connection->getConnection($command);
  1783. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  1784. continue;
  1785. }
  1786. try {
  1787. $cmdConnection->writeCommand($command);
  1788. }
  1789. catch (\Predis\CommunicationException $exception) {
  1790. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  1791. }
  1792. }
  1793. for ($i = 0; $i < $sizeofPipe; $i++) {
  1794. $command = $commands[$i];
  1795. unset($commands[$i]);
  1796. $cmdConnection = $connection->getConnection($command);
  1797. $connectionObjectHash = spl_object_hash($cmdConnection);
  1798. if (isset($connectionExceptions[$connectionObjectHash])) {
  1799. $values[] = $connectionExceptions[$connectionObjectHash];
  1800. continue;
  1801. }
  1802. try {
  1803. $response = $cmdConnection->readResponse($command);
  1804. $values[] = ($response instanceof \Iterator
  1805. ? iterator_to_array($response)
  1806. : $response
  1807. );
  1808. }
  1809. catch (\Predis\ServerException $exception) {
  1810. $values[] = $exception->toResponseError();
  1811. }
  1812. catch (\Predis\CommunicationException $exception) {
  1813. $values[] = $exception;
  1814. $connectionExceptions[$connectionObjectHash] = $exception;
  1815. }
  1816. }
  1817. return $values;
  1818. }
  1819. }
  1820. /* ------------------------------------------------------------------------- */
  1821. namespace Predis\Distribution;
  1822. interface IDistributionStrategy {
  1823. public function add($node, $weight = null);
  1824. public function remove($node);
  1825. public function get($key);
  1826. public function generateKey($value);
  1827. }
  1828. class EmptyRingException extends \Exception { }
  1829. class HashRing implements IDistributionStrategy {
  1830. const DEFAULT_REPLICAS = 128;
  1831. const DEFAULT_WEIGHT = 100;
  1832. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1833. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1834. $this->_replicas = $replicas;
  1835. $this->_nodes = array();
  1836. }
  1837. public function add($node, $weight = null) {
  1838. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1839. // last wins, thus the order in which nodes are added is significant.
  1840. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT);
  1841. $this->reset();
  1842. }
  1843. public function remove($node) {
  1844. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1845. // scratch, in order to reassign possible hashes with collisions to the
  1846. // right node according to the order in which they were added in the
  1847. // first place.
  1848. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1849. if ($this->_nodes[$i]['object'] === $node) {
  1850. array_splice($this->_nodes, $i, 1);
  1851. $this->reset();
  1852. break;
  1853. }
  1854. }
  1855. }
  1856. private function reset() {
  1857. unset($this->_ring);
  1858. unset($this->_ringKeys);
  1859. unset($this->_ringKeysCount);
  1860. }
  1861. private function isInitialized() {
  1862. return isset($this->_ringKeys);
  1863. }
  1864. private function computeTotalWeight() {
  1865. // TODO: array_reduce + lambda for PHP 5.3
  1866. $totalWeight = 0;
  1867. foreach ($this->_nodes as $node) {
  1868. $totalWeight += $node['weight'];
  1869. }
  1870. return $totalWeight;
  1871. }
  1872. private function initialize() {
  1873. if ($this->isInitialized()) {
  1874. return;
  1875. }
  1876. if (count($this->_nodes) === 0) {
  1877. throw new EmptyRingException('Cannot initialize empty hashring');
  1878. }
  1879. $this->_ring = array();
  1880. $totalWeight = $this->computeTotalWeight();
  1881. $nodesCount = count($this->_nodes);
  1882. foreach ($this->_nodes as $node) {
  1883. $weightRatio = $node['weight'] / $totalWeight;
  1884. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1885. }
  1886. ksort($this->_ring, SORT_NUMERIC);
  1887. $this->_ringKeys = array_keys($this->_ring);
  1888. $this->_ringKeysCount = count($this->_ringKeys);
  1889. }
  1890. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1891. $nodeObject = $node['object'];
  1892. $nodeHash = (string) $nodeObject;
  1893. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1894. for ($i = 0; $i < $replicas; $i++) {
  1895. $key = crc32("$nodeHash:$i");
  1896. $ring[$key] = $nodeObject;
  1897. }
  1898. }
  1899. public function generateKey($value) {
  1900. return crc32($value);
  1901. }
  1902. public function get($key) {
  1903. return $this->_ring[$this->getNodeKey($key)];
  1904. }
  1905. private function getNodeKey($key) {
  1906. $this->initialize();
  1907. $ringKeys = $this->_ringKeys;
  1908. $upper = $this->_ringKeysCount - 1;
  1909. $lower = 0;
  1910. while ($lower <= $upper) {
  1911. $index = ($lower + $upper) >> 1;
  1912. $item = $ringKeys[$index];
  1913. if ($item > $key) {
  1914. $upper = $index - 1;
  1915. }
  1916. else if ($item < $key) {
  1917. $lower = $index + 1;
  1918. }
  1919. else {
  1920. return $item;
  1921. }
  1922. }
  1923. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1924. }
  1925. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1926. // NOTE: binary search for the last item in _ringkeys with a value
  1927. // less or equal to the key. If no such item exists, return the
  1928. // last item.
  1929. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1930. }
  1931. }
  1932. class KetamaPureRing extends HashRing {
  1933. const DEFAULT_REPLICAS = 160;
  1934. public function __construct() {
  1935. parent::__construct($this::DEFAULT_REPLICAS);
  1936. }
  1937. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1938. $nodeObject = $node['object'];
  1939. $nodeHash = (string) $nodeObject;
  1940. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1941. for ($i = 0; $i < $replicas; $i++) {
  1942. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1943. foreach ($unpackedDigest as $key) {
  1944. $ring[$key] = $nodeObject;
  1945. }
  1946. }
  1947. }
  1948. public function generateKey($value) {
  1949. $hash = unpack('V', md5($value, true));
  1950. return $hash[1];
  1951. }
  1952. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1953. // NOTE: binary search for the first item in _ringkeys with a value
  1954. // greater or equal to the key. If no such item exists, return the
  1955. // first item.
  1956. return $lower < $ringKeysCount ? $lower : 0;
  1957. }
  1958. }
  1959. /* ------------------------------------------------------------------------- */
  1960. namespace Predis\Shared;
  1961. class Utils {
  1962. public static function isCluster(\Predis\IConnection $connection) {
  1963. return $connection instanceof \Predis\ConnectionCluster;
  1964. }
  1965. public static function onCommunicationException(\Predis\CommunicationException $exception) {
  1966. if ($exception->shouldResetConnection()) {
  1967. $connection = $exception->getConnection();
  1968. if ($connection->isConnected()) {
  1969. $connection->disconnect();
  1970. }
  1971. }
  1972. throw $exception;
  1973. }
  1974. }
  1975. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1976. protected $_position, $_current, $_replySize;
  1977. public function rewind() {
  1978. // NOOP
  1979. }
  1980. public function current() {
  1981. return $this->_current;
  1982. }
  1983. public function key() {
  1984. return $this->_position;
  1985. }
  1986. public function next() {
  1987. if (++$this->_position < $this->_replySize) {
  1988. $this->_current = $this->getValue();
  1989. }
  1990. return $this->_position;
  1991. }
  1992. public function valid() {
  1993. return $this->_position < $this->_replySize;
  1994. }
  1995. public function count() {
  1996. // NOTE: use count if you want to get the size of the current multi-bulk
  1997. // response without using iterator_count (which actually consumes
  1998. // our iterator to calculate the size, and we cannot perform a rewind)
  1999. return $this->_replySize;
  2000. }
  2001. protected abstract function getValue();
  2002. }
  2003. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  2004. private $_connection;
  2005. public function __construct(\Predis\Connection $connection, $size) {
  2006. $this->_connection = $connection;
  2007. $this->_reader = $connection->getResponseReader();
  2008. $this->_position = 0;
  2009. $this->_current = $size > 0 ? $this->getValue() : null;
  2010. $this->_replySize = $size;
  2011. }
  2012. public function __destruct() {
  2013. // when the iterator is garbage-collected (e.g. it goes out of the
  2014. // scope of a foreach) but it has not reached its end, we must sync
  2015. // the client with the queued elements that have not been read from
  2016. // the connection with the server.
  2017. $this->sync();
  2018. }
  2019. public function sync($drop = false) {
  2020. if ($drop == true) {
  2021. if ($this->valid()) {
  2022. $this->_position = $this->_replySize;
  2023. $this->_connection->disconnect();
  2024. }
  2025. }
  2026. else {
  2027. while ($this->valid()) {
  2028. $this->next();
  2029. }
  2030. }
  2031. }
  2032. protected function getValue() {
  2033. return $this->_reader->read($this->_connection);
  2034. }
  2035. }
  2036. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  2037. private $_iterator;
  2038. public function __construct(MultiBulkResponseIterator $iterator) {
  2039. $virtualSize = count($iterator) / 2;
  2040. $this->_iterator = $iterator;
  2041. $this->_position = 0;
  2042. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  2043. $this->_replySize = $virtualSize;
  2044. }
  2045. public function __destruct() {
  2046. $this->_iterator->sync();
  2047. }
  2048. protected function getValue() {
  2049. $k = $this->_iterator->current();
  2050. $this->_iterator->next();
  2051. $v = $this->_iterator->current();
  2052. $this->_iterator->next();
  2053. return array($k, $v);
  2054. }
  2055. }
  2056. /* ------------------------------------------------------------------------- */
  2057. namespace Predis\Commands;
  2058. /* miscellaneous commands */
  2059. class Ping extends \Predis\MultiBulkCommand {
  2060. public function canBeHashed() { return false; }
  2061. public function getCommandId() { return 'PING'; }
  2062. public function parseResponse($data) {
  2063. return $data === 'PONG' ? true : false;
  2064. }
  2065. }
  2066. class DoEcho extends \Predis\MultiBulkCommand {
  2067. public function canBeHashed() { return false; }
  2068. public function getCommandId() { return 'ECHO'; }
  2069. }
  2070. class Auth extends \Predis\MultiBulkCommand {
  2071. public function canBeHashed() { return false; }
  2072. public function getCommandId() { return 'AUTH'; }
  2073. }
  2074. /* connection handling */
  2075. class Quit extends \Predis\MultiBulkCommand {
  2076. public function canBeHashed() { return false; }
  2077. public function getCommandId() { return 'QUIT'; }
  2078. public function closesConnection() { return true; }
  2079. }
  2080. /* commands operating on string values */
  2081. class Set extends \Predis\MultiBulkCommand {
  2082. public function getCommandId() { return 'SET'; }
  2083. }
  2084. class SetExpire extends \Predis\MultiBulkCommand {
  2085. public function getCommandId() { return 'SETEX'; }
  2086. }
  2087. class SetPreserve extends \Predis\MultiBulkCommand {
  2088. public function getCommandId() { return 'SETNX'; }
  2089. public function parseResponse($data) { return (bool) $data; }
  2090. }
  2091. class SetMultiple extends \Predis\MultiBulkCommand {
  2092. public function canBeHashed() { return false; }
  2093. public function getCommandId() { return 'MSET'; }
  2094. public function filterArguments(Array $arguments) {
  2095. if (count($arguments) === 1 && is_array($arguments[0])) {
  2096. $flattenedKVs = array();
  2097. $args = &$arguments[0];
  2098. foreach ($args as $k => $v) {
  2099. $flattenedKVs[] = $k;
  2100. $flattenedKVs[] = $v;
  2101. }
  2102. return $flattenedKVs;
  2103. }
  2104. return $arguments;
  2105. }
  2106. }
  2107. class SetMultiplePreserve extends \Predis\Commands\SetMultiple {
  2108. public function canBeHashed() { return false; }
  2109. public function getCommandId() { return 'MSETNX'; }
  2110. public function parseResponse($data) { return (bool) $data; }
  2111. }
  2112. class Get extends \Predis\MultiBulkCommand {
  2113. public function getCommandId() { return 'GET'; }
  2114. }
  2115. class GetMultiple extends \Predis\MultiBulkCommand {
  2116. public function canBeHashed() { return false; }
  2117. public function getCommandId() { return 'MGET'; }
  2118. }
  2119. class GetSet extends \Predis\MultiBulkCommand {
  2120. public function getCommandId() { return 'GETSET'; }
  2121. }
  2122. class Increment extends \Predis\MultiBulkCommand {
  2123. public function getCommandId() { return 'INCR'; }
  2124. }
  2125. class IncrementBy extends \Predis\MultiBulkCommand {
  2126. public function getCommandId() { return 'INCRBY'; }
  2127. }
  2128. class Decrement extends \Predis\MultiBulkCommand {
  2129. public function getCommandId() { return 'DECR'; }
  2130. }
  2131. class DecrementBy extends \Predis\MultiBulkCommand {
  2132. public function getCommandId() { return 'DECRBY'; }
  2133. }
  2134. class Exists extends \Predis\MultiBulkCommand {
  2135. public function getCommandId() { return 'EXISTS'; }
  2136. public function parseResponse($data) { return (bool) $data; }
  2137. }
  2138. class Delete extends \Predis\MultiBulkCommand {
  2139. public function getCommandId() { return 'DEL'; }
  2140. }
  2141. class Type extends \Predis\MultiBulkCommand {
  2142. public function getCommandId() { return 'TYPE'; }
  2143. }
  2144. class Append extends \Predis\MultiBulkCommand {
  2145. public function getCommandId() { return 'APPEND'; }
  2146. }
  2147. class SetRange extends \Predis\MultiBulkCommand {
  2148. public function getCommandId() { return 'SETRANGE'; }
  2149. }
  2150. class Substr extends \Predis\MultiBulkCommand {
  2151. public function getCommandId() { return 'SUBSTR'; }
  2152. }
  2153. class SetBit extends \Predis\MultiBulkCommand {
  2154. public function getCommandId() { return 'SETBIT'; }
  2155. }
  2156. class GetBit extends \Predis\MultiBulkCommand {
  2157. public function getCommandId() { return 'GETBIT'; }
  2158. }
  2159. class Strlen extends \Predis\MultiBulkCommand {
  2160. public function getCommandId() { return 'STRLEN'; }
  2161. }
  2162. /* commands operating on the key space */
  2163. class Keys extends \Predis\MultiBulkCommand {
  2164. public function canBeHashed() { return false; }
  2165. public function getCommandId() { return 'KEYS'; }
  2166. }
  2167. class Keys_v1_2 extends Keys {
  2168. public function parseResponse($data) {
  2169. return explode(' ', $data);
  2170. }
  2171. }
  2172. class RandomKey extends \Predis\MultiBulkCommand {
  2173. public function canBeHashed() { return false; }
  2174. public function getCommandId() { return 'RANDOMKEY'; }
  2175. public function parseResponse($data) { return $data !== '' ? $data : null; }
  2176. }
  2177. class Rename extends \Predis\MultiBulkCommand {
  2178. public function canBeHashed() { return false; }
  2179. public function getCommandId() { return 'RENAME'; }
  2180. }
  2181. class RenamePreserve extends \Predis\MultiBulkCommand {
  2182. public function canBeHashed() { return false; }
  2183. public function getCommandId() { return 'RENAMENX'; }
  2184. public function parseResponse($data) { return (bool) $data; }
  2185. }
  2186. class Expire extends \Predis\MultiBulkCommand {
  2187. public function getCommandId() { return 'EXPIRE'; }
  2188. public function parseResponse($data) { return (bool) $data; }
  2189. }
  2190. class ExpireAt extends \Predis\MultiBulkCommand {
  2191. public function getCommandId() { return 'EXPIREAT'; }
  2192. public function parseResponse($data) { return (bool) $data; }
  2193. }
  2194. class Persist extends \Predis\MultiBulkCommand {
  2195. public function getCommandId() { return 'PERSIST'; }
  2196. public function parseResponse($data) { return (bool) $data; }
  2197. }
  2198. class DatabaseSize extends \Predis\MultiBulkCommand {
  2199. public function canBeHashed() { return false; }
  2200. public function getCommandId() { return 'DBSIZE'; }
  2201. }
  2202. class TimeToLive extends \Predis\MultiBulkCommand {
  2203. public function getCommandId() { return 'TTL'; }
  2204. }
  2205. /* commands operating on lists */
  2206. class ListPushTail extends \Predis\MultiBulkCommand {
  2207. public function getCommandId() { return 'RPUSH'; }
  2208. }
  2209. class ListPushTailX extends \Predis\MultiBulkCommand {
  2210. public function getCommandId() { return 'RPUSHX'; }
  2211. }
  2212. class ListPushHead extends \Predis\MultiBulkCommand {
  2213. public function getCommandId() { return 'LPUSH'; }
  2214. }
  2215. class ListPushHeadX extends \Predis\MultiBulkCommand {
  2216. public function getCommandId() { return 'LPUSHX'; }
  2217. }
  2218. class ListLength extends \Predis\MultiBulkCommand {
  2219. public function getCommandId() { return 'LLEN'; }
  2220. }
  2221. class ListRange extends \Predis\MultiBulkCommand {
  2222. public function getCommandId() { return 'LRANGE'; }
  2223. }
  2224. class ListTrim extends \Predis\MultiBulkCommand {
  2225. public function getCommandId() { return 'LTRIM'; }
  2226. }
  2227. class ListIndex extends \Predis\MultiBulkCommand {
  2228. public function getCommandId() { return 'LINDEX'; }
  2229. }
  2230. class ListSet extends \Predis\MultiBulkCommand {
  2231. public function getCommandId() { return 'LSET'; }
  2232. }
  2233. class ListRemove extends \Predis\MultiBulkCommand {
  2234. public function getCommandId() { return 'LREM'; }
  2235. }
  2236. class ListPopLastPushHead extends \Predis\MultiBulkCommand {
  2237. public function getCommandId() { return 'RPOPLPUSH'; }
  2238. }
  2239. class ListPopLastPushHeadBlocking extends \Predis\MultiBulkCommand {
  2240. public function getCommandId() { return 'BRPOPLPUSH'; }
  2241. }
  2242. class ListPopFirst extends \Predis\MultiBulkCommand {
  2243. public function getCommandId() { return 'LPOP'; }
  2244. }
  2245. class ListPopLast extends \Predis\MultiBulkCommand {
  2246. public function getCommandId() { return 'RPOP'; }
  2247. }
  2248. class ListPopFirstBlocking extends \Predis\MultiBulkCommand {
  2249. public function getCommandId() { return 'BLPOP'; }
  2250. }
  2251. class ListPopLastBlocking extends \Predis\MultiBulkCommand {
  2252. public function getCommandId() { return 'BRPOP'; }
  2253. }
  2254. class ListInsert extends \Predis\MultiBulkCommand {
  2255. public function getCommandId() { return 'LINSERT'; }
  2256. }
  2257. /* commands operating on sets */
  2258. class SetAdd extends \Predis\MultiBulkCommand {
  2259. public function getCommandId() { return 'SADD'; }
  2260. public function parseResponse($data) { return (bool) $data; }
  2261. }
  2262. class SetRemove extends \Predis\MultiBulkCommand {
  2263. public function getCommandId() { return 'SREM'; }
  2264. public function parseResponse($data) { return (bool) $data; }
  2265. }
  2266. class SetPop extends \Predis\MultiBulkCommand {
  2267. public function getCommandId() { return 'SPOP'; }
  2268. }
  2269. class SetMove extends \Predis\MultiBulkCommand {
  2270. public function canBeHashed() { return false; }
  2271. public function getCommandId() { return 'SMOVE'; }
  2272. public function parseResponse($data) { return (bool) $data; }
  2273. }
  2274. class SetCardinality extends \Predis\MultiBulkCommand {
  2275. public function getCommandId() { return 'SCARD'; }
  2276. }
  2277. class SetIsMember extends \Predis\MultiBulkCommand {
  2278. public function getCommandId() { return 'SISMEMBER'; }
  2279. public function parseResponse($data) { return (bool) $data; }
  2280. }
  2281. class SetIntersection extends \Predis\MultiBulkCommand {
  2282. public function getCommandId() { return 'SINTER'; }
  2283. }
  2284. class SetIntersectionStore extends \Predis\MultiBulkCommand {
  2285. public function getCommandId() { return 'SINTERSTORE'; }
  2286. }
  2287. class SetUnion extends \Predis\MultiBulkCommand {
  2288. public function getCommandId() { return 'SUNION'; }
  2289. }
  2290. class SetUnionStore extends \Predis\MultiBulkCommand {
  2291. public function getCommandId() { return 'SUNIONSTORE'; }
  2292. }
  2293. class SetDifference extends \Predis\MultiBulkCommand {
  2294. public function getCommandId() { return 'SDIFF'; }
  2295. }
  2296. class SetDifferenceStore extends \Predis\MultiBulkCommand {
  2297. public function getCommandId() { return 'SDIFFSTORE'; }
  2298. }
  2299. class SetMembers extends \Predis\MultiBulkCommand {
  2300. public function getCommandId() { return 'SMEMBERS'; }
  2301. }
  2302. class SetRandomMember extends \Predis\MultiBulkCommand {
  2303. public function getCommandId() { return 'SRANDMEMBER'; }
  2304. }
  2305. /* commands operating on sorted sets */
  2306. class ZSetAdd extends \Predis\MultiBulkCommand {
  2307. public function getCommandId() { return 'ZADD'; }
  2308. public function parseResponse($data) { return (bool) $data; }
  2309. }
  2310. class ZSetIncrementBy extends \Predis\MultiBulkCommand {
  2311. public function getCommandId() { return 'ZINCRBY'; }
  2312. }
  2313. class ZSetRemove extends \Predis\MultiBulkCommand {
  2314. public function getCommandId() { return 'ZREM'; }
  2315. public function parseResponse($data) { return (bool) $data; }
  2316. }
  2317. class ZSetUnionStore extends \Predis\MultiBulkCommand {
  2318. public function getCommandId() { return 'ZUNIONSTORE'; }
  2319. public function filterArguments(Array $arguments) {
  2320. $options = array();
  2321. $argc = count($arguments);
  2322. if ($argc > 2 && is_array($arguments[$argc - 1])) {
  2323. $options = $this->prepareOptions(array_pop($arguments));
  2324. }
  2325. if (is_array($arguments[1])) {
  2326. $arguments = array_merge(
  2327. array($arguments[0], count($arguments[1])),
  2328. $arguments[1]
  2329. );
  2330. }
  2331. return array_merge($arguments, $options);
  2332. }
  2333. private function prepareOptions($options) {
  2334. $opts = array_change_key_case($options, CASE_UPPER);
  2335. $finalizedOpts = array();
  2336. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  2337. $finalizedOpts[] = 'WEIGHTS';
  2338. foreach ($opts['WEIGHTS'] as $weight) {
  2339. $finalizedOpts[] = $weight;
  2340. }
  2341. }
  2342. if (isset($opts['AGGREGATE'])) {
  2343. $finalizedOpts[] = 'AGGREGATE';
  2344. $finalizedOpts[] = $opts['AGGREGATE'];
  2345. }
  2346. return $finalizedOpts;
  2347. }
  2348. }
  2349. class ZSetIntersectionStore extends \Predis\Commands\ZSetUnionStore {
  2350. public function getCommandId() { return 'ZINTERSTORE'; }
  2351. }
  2352. class ZSetRange extends \Predis\MultiBulkCommand {
  2353. private $_withScores = false;
  2354. public function getCommandId() { return 'ZRANGE'; }
  2355. public function filterArguments(Array $arguments) {
  2356. if (count($arguments) === 4) {
  2357. $lastType = gettype($arguments[3]);
  2358. if ($lastType === 'string' && strtolower($arguments[3]) === 'withscores') {
  2359. // used for compatibility with older versions
  2360. $arguments[3] = array('WITHSCORES' => true);
  2361. $lastType = 'array';
  2362. }
  2363. if ($lastType === 'array') {
  2364. $options = $this->prepareOptions(array_pop($arguments));
  2365. return array_merge($arguments, $options);
  2366. }
  2367. }
  2368. return $arguments;
  2369. }
  2370. protected function prepareOptions($options) {
  2371. $opts = array_change_key_case($options, CASE_UPPER);
  2372. $finalizedOpts = array();
  2373. if (isset($opts['WITHSCORES'])) {
  2374. $finalizedOpts[] = 'WITHSCORES';
  2375. $this->_withScores = true;
  2376. }
  2377. return $finalizedOpts;
  2378. }
  2379. public function parseResponse($data) {
  2380. if ($this->_withScores) {
  2381. if ($data instanceof \Iterator) {
  2382. return new \Predis\Shared\MultiBulkResponseKVIterator($data);
  2383. }
  2384. $result = array();
  2385. for ($i = 0; $i < count($data); $i++) {
  2386. $result[] = array($data[$i], $data[++$i]);
  2387. }
  2388. return $result;
  2389. }
  2390. return $data;
  2391. }
  2392. }
  2393. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  2394. public function getCommandId() { return 'ZREVRANGE'; }
  2395. }
  2396. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  2397. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  2398. protected function prepareOptions($options) {
  2399. $opts = array_change_key_case($options, CASE_UPPER);
  2400. $finalizedOpts = array();
  2401. if (isset($opts['LIMIT']) && is_array($opts['LIMIT'])) {
  2402. $limit = array_change_key_case($opts['LIMIT'], CASE_UPPER);
  2403. $finalizedOpts[] = 'LIMIT';
  2404. $finalizedOpts[] = isset($limit['OFFSET']) ? $limit['OFFSET'] : $limit[0];
  2405. $finalizedOpts[] = isset($limit['COUNT']) ? $limit['COUNT'] : $limit[1];
  2406. }
  2407. return array_merge($finalizedOpts, parent::prepareOptions($options));
  2408. }
  2409. }
  2410. class ZSetReverseRangeByScore extends \Predis\Commands\ZSetRangeByScore {
  2411. public function getCommandId() { return 'ZREVRANGEBYSCORE'; }
  2412. }
  2413. class ZSetCount extends \Predis\MultiBulkCommand {
  2414. public function getCommandId() { return 'ZCOUNT'; }
  2415. }
  2416. class ZSetCardinality extends \Predis\MultiBulkCommand {
  2417. public function getCommandId() { return 'ZCARD'; }
  2418. }
  2419. class ZSetScore extends \Predis\MultiBulkCommand {
  2420. public function getCommandId() { return 'ZSCORE'; }
  2421. }
  2422. class ZSetRemoveRangeByScore extends \Predis\MultiBulkCommand {
  2423. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  2424. }
  2425. class ZSetRank extends \Predis\MultiBulkCommand {
  2426. public function getCommandId() { return 'ZRANK'; }
  2427. }
  2428. class ZSetReverseRank extends \Predis\MultiBulkCommand {
  2429. public function getCommandId() { return 'ZREVRANK'; }
  2430. }
  2431. class ZSetRemoveRangeByRank extends \Predis\MultiBulkCommand {
  2432. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  2433. }
  2434. /* commands operating on hashes */
  2435. class HashSet extends \Predis\MultiBulkCommand {
  2436. public function getCommandId() { return 'HSET'; }
  2437. public function parseResponse($data) { return (bool) $data; }
  2438. }
  2439. class HashSetPreserve extends \Predis\MultiBulkCommand {
  2440. public function getCommandId() { return 'HSETNX'; }
  2441. public function parseResponse($data) { return (bool) $data; }
  2442. }
  2443. class HashSetMultiple extends \Predis\MultiBulkCommand {
  2444. public function getCommandId() { return 'HMSET'; }
  2445. public function filterArguments(Array $arguments) {
  2446. if (count($arguments) === 2 && is_array($arguments[1])) {
  2447. $flattenedKVs = array($arguments[0]);
  2448. $args = &$arguments[1];
  2449. foreach ($args as $k => $v) {
  2450. $flattenedKVs[] = $k;
  2451. $flattenedKVs[] = $v;
  2452. }
  2453. return $flattenedKVs;
  2454. }
  2455. return $arguments;
  2456. }
  2457. }
  2458. class HashIncrementBy extends \Predis\MultiBulkCommand {
  2459. public function getCommandId() { return 'HINCRBY'; }
  2460. }
  2461. class HashGet extends \Predis\MultiBulkCommand {
  2462. public function getCommandId() { return 'HGET'; }
  2463. }
  2464. class HashGetMultiple extends \Predis\MultiBulkCommand {
  2465. public function getCommandId() { return 'HMGET'; }
  2466. public function filterArguments(Array $arguments) {
  2467. if (count($arguments) === 2 && is_array($arguments[1])) {
  2468. $flattenedKVs = array($arguments[0]);
  2469. $args = &$arguments[1];
  2470. foreach ($args as $v) {
  2471. $flattenedKVs[] = $v;
  2472. }
  2473. return $flattenedKVs;
  2474. }
  2475. return $arguments;
  2476. }
  2477. }
  2478. class HashDelete extends \Predis\MultiBulkCommand {
  2479. public function getCommandId() { return 'HDEL'; }
  2480. public function parseResponse($data) { return (bool) $data; }
  2481. }
  2482. class HashExists extends \Predis\MultiBulkCommand {
  2483. public function getCommandId() { return 'HEXISTS'; }
  2484. public function parseResponse($data) { return (bool) $data; }
  2485. }
  2486. class HashLength extends \Predis\MultiBulkCommand {
  2487. public function getCommandId() { return 'HLEN'; }
  2488. }
  2489. class HashKeys extends \Predis\MultiBulkCommand {
  2490. public function getCommandId() { return 'HKEYS'; }
  2491. }
  2492. class HashValues extends \Predis\MultiBulkCommand {
  2493. public function getCommandId() { return 'HVALS'; }
  2494. }
  2495. class HashGetAll extends \Predis\MultiBulkCommand {
  2496. public function getCommandId() { return 'HGETALL'; }
  2497. public function parseResponse($data) {
  2498. if ($data instanceof \Iterator) {
  2499. return new \Predis\Shared\MultiBulkResponseKVIterator($data);
  2500. }
  2501. $result = array();
  2502. for ($i = 0; $i < count($data); $i++) {
  2503. $result[$data[$i]] = $data[++$i];
  2504. }
  2505. return $result;
  2506. }
  2507. }
  2508. /* multiple databases handling commands */
  2509. class SelectDatabase extends \Predis\MultiBulkCommand {
  2510. public function canBeHashed() { return false; }
  2511. public function getCommandId() { return 'SELECT'; }
  2512. }
  2513. class MoveKey extends \Predis\MultiBulkCommand {
  2514. public function canBeHashed() { return false; }
  2515. public function getCommandId() { return 'MOVE'; }
  2516. public function parseResponse($data) { return (bool) $data; }
  2517. }
  2518. class FlushDatabase extends \Predis\MultiBulkCommand {
  2519. public function canBeHashed() { return false; }
  2520. public function getCommandId() { return 'FLUSHDB'; }
  2521. }
  2522. class FlushAll extends \Predis\MultiBulkCommand {
  2523. public function canBeHashed() { return false; }
  2524. public function getCommandId() { return 'FLUSHALL'; }
  2525. }
  2526. /* sorting */
  2527. class Sort extends \Predis\MultiBulkCommand {
  2528. public function getCommandId() { return 'SORT'; }
  2529. public function filterArguments(Array $arguments) {
  2530. if (count($arguments) === 1) {
  2531. return $arguments;
  2532. }
  2533. $query = array($arguments[0]);
  2534. $sortParams = array_change_key_case($arguments[1], CASE_UPPER);
  2535. if (isset($sortParams['BY'])) {
  2536. $query[] = 'BY';
  2537. $query[] = $sortParams['BY'];
  2538. }
  2539. if (isset($sortParams['GET'])) {
  2540. $getargs = $sortParams['GET'];
  2541. if (is_array($getargs)) {
  2542. foreach ($getargs as $getarg) {
  2543. $query[] = 'GET';
  2544. $query[] = $getarg;
  2545. }
  2546. }
  2547. else {
  2548. $query[] = 'GET';
  2549. $query[] = $getargs;
  2550. }
  2551. }
  2552. if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
  2553. && count($sortParams['LIMIT']) == 2) {
  2554. $query[] = 'LIMIT';
  2555. $query[] = $sortParams['LIMIT'][0];
  2556. $query[] = $sortParams['LIMIT'][1];
  2557. }
  2558. if (isset($sortParams['SORT'])) {
  2559. $query[] = strtoupper($sortParams['SORT']);
  2560. }
  2561. if (isset($sortParams['ALPHA']) && $sortParams['ALPHA'] == true) {
  2562. $query[] = 'ALPHA';
  2563. }
  2564. if (isset($sortParams['STORE'])) {
  2565. $query[] = 'STORE';
  2566. $query[] = $sortParams['STORE'];
  2567. }
  2568. return $query;
  2569. }
  2570. }
  2571. /* transactions */
  2572. class Multi extends \Predis\MultiBulkCommand {
  2573. public function canBeHashed() { return false; }
  2574. public function getCommandId() { return 'MULTI'; }
  2575. }
  2576. class Exec extends \Predis\MultiBulkCommand {
  2577. public function canBeHashed() { return false; }
  2578. public function getCommandId() { return 'EXEC'; }
  2579. }
  2580. class Discard extends \Predis\MultiBulkCommand {
  2581. public function canBeHashed() { return false; }
  2582. public function getCommandId() { return 'DISCARD'; }
  2583. }
  2584. class Watch extends \Predis\MultiBulkCommand {
  2585. public function canBeHashed() { return false; }
  2586. public function getCommandId() { return 'WATCH'; }
  2587. public function filterArguments(Array $arguments) {
  2588. if (isset($arguments[0]) && is_array($arguments[0])) {
  2589. return $arguments[0];
  2590. }
  2591. return $arguments;
  2592. }
  2593. public function parseResponse($data) { return (bool) $data; }
  2594. }
  2595. class Unwatch extends \Predis\MultiBulkCommand {
  2596. public function canBeHashed() { return false; }
  2597. public function getCommandId() { return 'UNWATCH'; }
  2598. public function parseResponse($data) { return (bool) $data; }
  2599. }
  2600. /* publish/subscribe */
  2601. class Subscribe extends \Predis\MultiBulkCommand {
  2602. public function canBeHashed() { return false; }
  2603. public function getCommandId() { return 'SUBSCRIBE'; }
  2604. }
  2605. class Unsubscribe extends \Predis\MultiBulkCommand {
  2606. public function canBeHashed() { return false; }
  2607. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2608. }
  2609. class SubscribeByPattern extends \Predis\MultiBulkCommand {
  2610. public function canBeHashed() { return false; }
  2611. public function getCommandId() { return 'PSUBSCRIBE'; }
  2612. }
  2613. class UnsubscribeByPattern extends \Predis\MultiBulkCommand {
  2614. public function canBeHashed() { return false; }
  2615. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  2616. }
  2617. class Publish extends \Predis\MultiBulkCommand {
  2618. public function canBeHashed() { return false; }
  2619. public function getCommandId() { return 'PUBLISH'; }
  2620. }
  2621. /* persistence control commands */
  2622. class Save extends \Predis\MultiBulkCommand {
  2623. public function canBeHashed() { return false; }
  2624. public function getCommandId() { return 'SAVE'; }
  2625. }
  2626. class BackgroundSave extends \Predis\MultiBulkCommand {
  2627. public function canBeHashed() { return false; }
  2628. public function getCommandId() { return 'BGSAVE'; }
  2629. public function parseResponse($data) {
  2630. if ($data == 'Background saving started') {
  2631. return true;
  2632. }
  2633. return $data;
  2634. }
  2635. }
  2636. class BackgroundRewriteAppendOnlyFile extends \Predis\MultiBulkCommand {
  2637. public function canBeHashed() { return false; }
  2638. public function getCommandId() { return 'BGREWRITEAOF'; }
  2639. public function parseResponse($data) {
  2640. return $data == 'Background append only file rewriting started';
  2641. }
  2642. }
  2643. class LastSave extends \Predis\MultiBulkCommand {
  2644. public function canBeHashed() { return false; }
  2645. public function getCommandId() { return 'LASTSAVE'; }
  2646. }
  2647. class Shutdown extends \Predis\MultiBulkCommand {
  2648. public function canBeHashed() { return false; }
  2649. public function getCommandId() { return 'SHUTDOWN'; }
  2650. public function closesConnection() { return true; }
  2651. }
  2652. /* remote server control commands */
  2653. class Info extends \Predis\MultiBulkCommand {
  2654. public function canBeHashed() { return false; }
  2655. public function getCommandId() { return 'INFO'; }
  2656. public function parseResponse($data) {
  2657. $info = array();
  2658. $infoLines = explode("\r\n", $data, -1);
  2659. foreach ($infoLines as $row) {
  2660. @list($k, $v) = explode(':', $row);
  2661. if ($row === '' || !isset($v)) {
  2662. continue;
  2663. }
  2664. if (!preg_match('/^db\d+$/', $k)) {
  2665. if ($k === 'allocation_stats') {
  2666. $info[$k] = $this->parseAllocationStats($v);
  2667. continue;
  2668. }
  2669. $info[$k] = $v;
  2670. }
  2671. else {
  2672. $info[$k] = $this->parseDatabaseStats($v);
  2673. }
  2674. }
  2675. return $info;
  2676. }
  2677. protected function parseDatabaseStats($str) {
  2678. $db = array();
  2679. foreach (explode(',', $str) as $dbvar) {
  2680. list($dbvk, $dbvv) = explode('=', $dbvar);
  2681. $db[trim($dbvk)] = $dbvv;
  2682. }
  2683. return $db;
  2684. }
  2685. protected function parseAllocationStats($str) {
  2686. $stats = array();
  2687. foreach (explode(',', $str) as $kv) {
  2688. @list($size, $objects, $extra) = explode('=', $kv);
  2689. // hack to prevent incorrect values when parsing the >=256 key
  2690. if (isset($extra)) {
  2691. $size = ">=$objects";
  2692. $objects = $extra;
  2693. }
  2694. $stats[$size] = $objects;
  2695. }
  2696. return $stats;
  2697. }
  2698. }
  2699. class Info_v24 extends Info {
  2700. public function parseResponse($data) {
  2701. $info = array();
  2702. $current = null;
  2703. $infoLines = explode("\r\n", $data, -1);
  2704. foreach ($infoLines as $row) {
  2705. if ($row === '') {
  2706. continue;
  2707. }
  2708. if (preg_match('/^# (\w+)$/', $row, $matches)) {
  2709. $info[$matches[1]] = array();
  2710. $current = &$info[$matches[1]];
  2711. continue;
  2712. }
  2713. list($k, $v) = explode(':', $row);
  2714. if (!preg_match('/^db\d+$/', $k)) {
  2715. if ($k === 'allocation_stats') {
  2716. $current[$k] = $this->parseAllocationStats($v);
  2717. continue;
  2718. }
  2719. $current[$k] = $v;
  2720. }
  2721. else {
  2722. $current[$k] = $this->parseDatabaseStats($v);
  2723. }
  2724. }
  2725. return $info;
  2726. }
  2727. }
  2728. class SlaveOf extends \Predis\MultiBulkCommand {
  2729. public function canBeHashed() { return false; }
  2730. public function getCommandId() { return 'SLAVEOF'; }
  2731. public function filterArguments(Array $arguments) {
  2732. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2733. return array('NO', 'ONE');
  2734. }
  2735. return $arguments;
  2736. }
  2737. }
  2738. class Config extends \Predis\MultiBulkCommand {
  2739. public function canBeHashed() { return false; }
  2740. public function getCommandId() { return 'CONFIG'; }
  2741. }
  2742. ?>