Predis.php 95 KB

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