Predis.php 95 KB

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