Predis.php 109 KB

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