Predis.php 104 KB

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