Predis.php 88 KB

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