Predis.php 95 KB

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