Predis.php 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250
  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->setConnection($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) {
  38. if ($parameters === null) {
  39. return $this->createConnection(null);
  40. }
  41. if (!(is_array($parameters) || is_string($parameters)
  42. || $parameters instanceof IConnection
  43. || $parameters instanceof ConnectionParameters)) {
  44. throw new \InvalidArgumentException(
  45. 'Array, String, Predis\ConnectionParameters or Predis\Network\IConnection expected'
  46. );
  47. }
  48. if (is_array($parameters) && isset($parameters[0])) {
  49. $cluster = new ConnectionCluster($this->_options->key_distribution);
  50. foreach ($parameters as $shardParams) {
  51. $cluster->add($this->createConnection($shardParams));
  52. }
  53. return $cluster;
  54. }
  55. else if ($parameters instanceof IConnectionCluster) {
  56. return $parameters;
  57. }
  58. else {
  59. return $this->createConnection($parameters);
  60. }
  61. }
  62. private function createConnection($parameters) {
  63. $params = null;
  64. $connection = null;
  65. if ($parameters instanceof IConnectionSingle) {
  66. $connection = $parameters;
  67. $params = $connection->getParameters();
  68. }
  69. else {
  70. $params = $parameters instanceof ConnectionsParameters
  71. ? $parameters
  72. : new ConnectionParameters($parameters);
  73. $connection = ConnectionFactory::create($params);
  74. }
  75. $options = $this->_options;
  76. $protocol = $connection->getProtocol();
  77. $protocol->setOption('iterable_multibulk', $options->iterable_multibulk);
  78. $protocol->setOption('throw_on_error', $options->throw_on_error);
  79. return $this->pushInitCommands($connection);
  80. }
  81. private function pushInitCommands(IConnectionSingle $connection) {
  82. $params = $connection->getParameters();
  83. if (isset($params->password)) {
  84. $connection->pushInitCommand($this->createCommand(
  85. 'auth', array($params->password)
  86. ));
  87. }
  88. if (isset($params->database)) {
  89. $connection->pushInitCommand($this->createCommand(
  90. 'select', array($params->database)
  91. ));
  92. }
  93. return $connection;
  94. }
  95. private function setConnection(IConnection $connection) {
  96. $this->_connection = $connection;
  97. }
  98. public function getProfile() {
  99. return $this->_profile;
  100. }
  101. public function getOptions() {
  102. return $this->_options;
  103. }
  104. public function getClientFor($connectionAlias) {
  105. if (!Utils::isCluster($this->_connection)) {
  106. throw new ClientException(
  107. 'This method is supported only when the client is connected to a cluster of connections'
  108. );
  109. }
  110. $connection = $this->_connection->getConnectionById($connectionAlias);
  111. if ($connection === null) {
  112. throw new \InvalidArgumentException(
  113. "Invalid connection alias: '$connectionAlias'"
  114. );
  115. }
  116. $newClient = new Client();
  117. $newClient->setupClient($this->_options);
  118. $newClient->setConnection($connection);
  119. return $newClient;
  120. }
  121. public function connect() {
  122. $this->_connection->connect();
  123. }
  124. public function disconnect() {
  125. $this->_connection->disconnect();
  126. }
  127. public function isConnected() {
  128. return $this->_connection->isConnected();
  129. }
  130. public function getConnection($id = null) {
  131. $connection = $this->_connection;
  132. if (!isset($id)) {
  133. return $connection;
  134. }
  135. $isCluster = Utils::isCluster($connection);
  136. return $isCluster ? $connection->getConnectionById($id) : $connection;
  137. }
  138. public function __call($method, $arguments) {
  139. $command = $this->_profile->createCommand($method, $arguments);
  140. return $this->_connection->executeCommand($command);
  141. }
  142. public function createCommand($method, $arguments = array()) {
  143. return $this->_profile->createCommand($method, $arguments);
  144. }
  145. public function executeCommand(ICommand $command) {
  146. return $this->_connection->executeCommand($command);
  147. }
  148. public function executeCommandOnShards(ICommand $command) {
  149. if (Utils::isCluster($this->_connection)) {
  150. $replies = array();
  151. foreach ($this->_connection as $connection) {
  152. $replies[] = $connection->executeCommand($command);
  153. }
  154. return $replies;
  155. }
  156. return array($this->_connection->executeCommand($command));
  157. }
  158. private function sharedInitializer($argv, $initializer) {
  159. $argc = count($argv);
  160. if ($argc === 0) {
  161. return $this->$initializer();
  162. }
  163. else if ($argc === 1) {
  164. list($arg0) = $argv;
  165. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  166. }
  167. else if ($argc === 2) {
  168. list($arg0, $arg1) = $argv;
  169. return $this->$initializer($arg0, $arg1);
  170. }
  171. return $this->$initializer($this, $arguments);
  172. }
  173. public function pipeline(/* arguments */) {
  174. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  175. }
  176. private function initPipeline(Array $options = null, $pipelineBlock = null) {
  177. $pipeline = null;
  178. if (isset($options)) {
  179. if (isset($options['safe']) && $options['safe'] == true) {
  180. $connection = $this->_connection;
  181. $pipeline = new CommandPipeline($this,
  182. Utils::isCluster($connection)
  183. ? new Pipeline\SafeClusterExecutor($connection)
  184. : new Pipeline\SafeExecutor($connection)
  185. );
  186. }
  187. else {
  188. $pipeline = new CommandPipeline($this);
  189. }
  190. }
  191. return $this->pipelineExecute(
  192. $pipeline ?: new CommandPipeline($this), $pipelineBlock
  193. );
  194. }
  195. private function pipelineExecute(CommandPipeline $pipeline, $block) {
  196. return $block !== null ? $pipeline->execute($block) : $pipeline;
  197. }
  198. public function multiExec(/* arguments */) {
  199. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  200. }
  201. private function initMultiExec(Array $options = null, $transBlock = null) {
  202. $multi = isset($options) ? new MultiExecContext($this, $options) : new MultiExecContext($this);
  203. return $transBlock !== null ? $multi->execute($transBlock) : $multi;
  204. }
  205. public function pubSubContext() {
  206. return new PubSubContext($this);
  207. }
  208. }
  209. class CommandPipeline {
  210. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running, $_executor;
  211. public function __construct(Client $redisClient, IPipelineExecutor $executor = null) {
  212. $this->_redisClient = $redisClient;
  213. $this->_executor = $executor ?: new Pipeline\StandardExecutor();
  214. $this->_pipelineBuffer = array();
  215. $this->_returnValues = array();
  216. }
  217. public function __call($method, $arguments) {
  218. $command = $this->_redisClient->createCommand($method, $arguments);
  219. $this->recordCommand($command);
  220. return $this;
  221. }
  222. private function recordCommand(ICommand $command) {
  223. $this->_pipelineBuffer[] = $command;
  224. }
  225. public function flushPipeline() {
  226. if (count($this->_pipelineBuffer) > 0) {
  227. $connection = $this->_redisClient->getConnection();
  228. $this->_returnValues = array_merge(
  229. $this->_returnValues,
  230. $this->_executor->execute($connection, $this->_pipelineBuffer)
  231. );
  232. $this->_pipelineBuffer = array();
  233. }
  234. return $this;
  235. }
  236. private function setRunning($bool) {
  237. if ($bool == true && $this->_running == true) {
  238. throw new ClientException("This pipeline is already opened");
  239. }
  240. $this->_running = $bool;
  241. }
  242. public function execute($block = null) {
  243. if ($block && !is_callable($block)) {
  244. throw new \InvalidArgumentException('Argument passed must be a callable object');
  245. }
  246. $this->setRunning(true);
  247. $pipelineBlockException = null;
  248. try {
  249. if ($block !== null) {
  250. $block($this);
  251. }
  252. $this->flushPipeline();
  253. }
  254. catch (\Exception $exception) {
  255. $pipelineBlockException = $exception;
  256. }
  257. $this->setRunning(false);
  258. if ($pipelineBlockException !== null) {
  259. throw $pipelineBlockException;
  260. }
  261. return $this->_returnValues;
  262. }
  263. }
  264. class MultiExecContext {
  265. private $_initialized, $_discarded, $_insideBlock, $_checkAndSet;
  266. private $_redisClient, $_options, $_commands;
  267. private $_supportsWatch;
  268. public function __construct(Client $redisClient, Array $options = null) {
  269. $this->checkCapabilities($redisClient);
  270. $this->_options = $options ?: array();
  271. $this->_redisClient = $redisClient;
  272. $this->reset();
  273. }
  274. private function checkCapabilities(Client $redisClient) {
  275. if (Utils::isCluster($redisClient->getConnection())) {
  276. throw new ClientException(
  277. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  278. );
  279. }
  280. $profile = $redisClient->getProfile();
  281. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  282. throw new ClientException(
  283. 'The current profile does not support MULTI, EXEC and DISCARD commands'
  284. );
  285. }
  286. $this->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  287. }
  288. private function isWatchSupported() {
  289. if ($this->_supportsWatch === false) {
  290. throw new ClientException(
  291. 'The current profile does not support WATCH and UNWATCH commands'
  292. );
  293. }
  294. }
  295. private function reset() {
  296. $this->_initialized = false;
  297. $this->_discarded = false;
  298. $this->_checkAndSet = false;
  299. $this->_insideBlock = false;
  300. $this->_commands = array();
  301. }
  302. private function initialize() {
  303. if ($this->_initialized === true) {
  304. return;
  305. }
  306. $options = &$this->_options;
  307. $this->_checkAndSet = isset($options['cas']) && $options['cas'];
  308. if (isset($options['watch'])) {
  309. $this->watch($options['watch']);
  310. }
  311. if (!$this->_checkAndSet || ($this->_discarded && $this->_checkAndSet)) {
  312. $this->_redisClient->multi();
  313. if ($this->_discarded) {
  314. $this->_checkAndSet = false;
  315. }
  316. }
  317. $this->_initialized = true;
  318. $this->_discarded = false;
  319. }
  320. public function __call($method, $arguments) {
  321. $this->initialize();
  322. $client = $this->_redisClient;
  323. if ($this->_checkAndSet) {
  324. return call_user_func_array(array($client, $method), $arguments);
  325. }
  326. $command = $client->createCommand($method, $arguments);
  327. $response = $client->executeCommand($command);
  328. if (!isset($response->queued)) {
  329. $this->malformedServerResponse(
  330. 'The server did not respond with a QUEUED status reply'
  331. );
  332. }
  333. $this->_commands[] = $command;
  334. return $this;
  335. }
  336. public function watch($keys) {
  337. $this->isWatchSupported();
  338. if ($this->_initialized && !$this->_checkAndSet) {
  339. throw new ClientException('WATCH inside MULTI is not allowed');
  340. }
  341. return $this->_redisClient->watch($keys);
  342. }
  343. public function multi() {
  344. if ($this->_initialized && $this->_checkAndSet) {
  345. $this->_checkAndSet = false;
  346. $this->_redisClient->multi();
  347. return $this;
  348. }
  349. $this->initialize();
  350. return $this;
  351. }
  352. public function unwatch() {
  353. $this->isWatchSupported();
  354. $this->_redisClient->unwatch();
  355. return $this;
  356. }
  357. public function discard() {
  358. $this->_redisClient->discard();
  359. $this->reset();
  360. $this->_discarded = true;
  361. return $this;
  362. }
  363. public function exec() {
  364. return $this->execute();
  365. }
  366. private function checkBeforeExecution($block) {
  367. if ($this->_insideBlock === true) {
  368. throw new ClientException(
  369. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  370. );
  371. }
  372. if ($block) {
  373. if (!is_callable($block)) {
  374. throw new \InvalidArgumentException(
  375. 'Argument passed must be a callable object'
  376. );
  377. }
  378. if (count($this->_commands) > 0) {
  379. throw new ClientException(
  380. 'Cannot execute a transaction block after using fluent interface'
  381. );
  382. }
  383. }
  384. if (isset($this->_options['retry']) && !isset($block)) {
  385. $this->discard();
  386. throw new \InvalidArgumentException(
  387. 'Automatic retries can be used only when a transaction block is provided'
  388. );
  389. }
  390. }
  391. public function execute($block = null) {
  392. $this->checkBeforeExecution($block);
  393. $reply = null;
  394. $returnValues = array();
  395. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  396. do {
  397. $blockException = null;
  398. if ($block !== null) {
  399. $this->_insideBlock = true;
  400. try {
  401. $block($this);
  402. }
  403. catch (CommunicationException $exception) {
  404. $blockException = $exception;
  405. }
  406. catch (ServerException $exception) {
  407. $blockException = $exception;
  408. }
  409. catch (\Exception $exception) {
  410. $blockException = $exception;
  411. if ($this->_initialized === true) {
  412. $this->discard();
  413. }
  414. }
  415. $this->_insideBlock = false;
  416. if ($blockException !== null) {
  417. throw $blockException;
  418. }
  419. }
  420. if ($this->_initialized === false || count($this->_commands) == 0) {
  421. return;
  422. }
  423. $reply = $this->_redisClient->exec();
  424. if ($reply === null) {
  425. if ($attemptsLeft === 0) {
  426. throw new AbortedMultiExec(
  427. 'The current transaction has been aborted by the server'
  428. );
  429. }
  430. $this->reset();
  431. continue;
  432. }
  433. break;
  434. } while ($attemptsLeft-- > 0);
  435. $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  436. $sizeofReplies = count($execReply);
  437. $commands = &$this->_commands;
  438. if ($sizeofReplies !== count($commands)) {
  439. $this->malformedServerResponse(
  440. 'Unexpected number of responses for a MultiExecContext'
  441. );
  442. }
  443. for ($i = 0; $i < $sizeofReplies; $i++) {
  444. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  445. ? iterator_to_array($execReply[$i])
  446. : $execReply[$i]
  447. );
  448. unset($commands[$i]);
  449. }
  450. return $returnValues;
  451. }
  452. private function malformedServerResponse($message) {
  453. // Since a MULTI/EXEC block cannot be initialized over a clustered
  454. // connection, we can safely assume that Predis\Client::getConnection()
  455. // will always return an instance of Predis\Connection.
  456. Utils::onCommunicationException(new MalformedServerResponse(
  457. $this->_redisClient->getConnection(), $message
  458. ));
  459. }
  460. }
  461. class PubSubContext implements \Iterator {
  462. const SUBSCRIBE = 'subscribe';
  463. const UNSUBSCRIBE = 'unsubscribe';
  464. const PSUBSCRIBE = 'psubscribe';
  465. const PUNSUBSCRIBE = 'punsubscribe';
  466. const MESSAGE = 'message';
  467. const PMESSAGE = 'pmessage';
  468. const STATUS_VALID = 0x0001;
  469. const STATUS_SUBSCRIBED = 0x0010;
  470. const STATUS_PSUBSCRIBED = 0x0100;
  471. private $_redisClient, $_subscriptions, $_isStillValid, $_position;
  472. public function __construct(Client $redisClient) {
  473. $this->checkCapabilities($redisClient);
  474. $this->_redisClient = $redisClient;
  475. $this->_statusFlags = self::STATUS_VALID;
  476. }
  477. public function __destruct() {
  478. $this->closeContext();
  479. }
  480. private function checkCapabilities(Client $redisClient) {
  481. if (Utils::isCluster($redisClient->getConnection())) {
  482. throw new ClientException(
  483. 'Cannot initialize a PUB/SUB context over a cluster of connections'
  484. );
  485. }
  486. $profile = $redisClient->getProfile();
  487. $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
  488. if ($profile->supportsCommands($commands) === false) {
  489. throw new ClientException(
  490. 'The current profile does not support PUB/SUB related commands'
  491. );
  492. }
  493. }
  494. private function isFlagSet($value) {
  495. return ($this->_statusFlags & $value) === $value;
  496. }
  497. public function subscribe(/* arguments */) {
  498. $this->writeCommand(self::SUBSCRIBE, func_get_args());
  499. $this->_statusFlags |= self::STATUS_SUBSCRIBED;
  500. }
  501. public function unsubscribe(/* arguments */) {
  502. $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
  503. }
  504. public function psubscribe(/* arguments */) {
  505. $this->writeCommand(self::PSUBSCRIBE, func_get_args());
  506. $this->_statusFlags |= self::STATUS_PSUBSCRIBED;
  507. }
  508. public function punsubscribe(/* arguments */) {
  509. $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
  510. }
  511. public function closeContext() {
  512. if ($this->valid()) {
  513. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  514. $this->unsubscribe();
  515. }
  516. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  517. $this->punsubscribe();
  518. }
  519. }
  520. }
  521. private function writeCommand($method, $arguments) {
  522. if (count($arguments) === 1 && is_array($arguments[0])) {
  523. $arguments = $arguments[0];
  524. }
  525. $command = $this->_redisClient->createCommand($method, $arguments);
  526. $this->_redisClient->getConnection()->writeCommand($command);
  527. }
  528. public function rewind() {
  529. // NOOP
  530. }
  531. public function current() {
  532. return $this->getValue();
  533. }
  534. public function key() {
  535. return $this->_position;
  536. }
  537. public function next() {
  538. if ($this->isFlagSet(self::STATUS_VALID)) {
  539. $this->_position++;
  540. }
  541. return $this->_position;
  542. }
  543. public function valid() {
  544. $subscriptions = self::STATUS_SUBSCRIBED + self::STATUS_PSUBSCRIBED;
  545. return $this->isFlagSet(self::STATUS_VALID)
  546. && ($this->_statusFlags & $subscriptions) > 0;
  547. }
  548. private function invalidate() {
  549. $this->_statusFlags = 0x0000;
  550. }
  551. private function getValue() {
  552. $connection = $this->_redisClient->getConnection();
  553. $protocol = $connection->getProtocol();
  554. $response = $protocol->read($connection);
  555. switch ($response[0]) {
  556. case self::SUBSCRIBE:
  557. case self::UNSUBSCRIBE:
  558. case self::PSUBSCRIBE:
  559. case self::PUNSUBSCRIBE:
  560. if ($response[2] === 0) {
  561. $this->invalidate();
  562. }
  563. case self::MESSAGE:
  564. return (object) array(
  565. 'kind' => $response[0],
  566. 'channel' => $response[1],
  567. 'payload' => $response[2],
  568. );
  569. case self::PMESSAGE:
  570. return (object) array(
  571. 'kind' => $response[0],
  572. 'pattern' => $response[1],
  573. 'channel' => $response[2],
  574. 'payload' => $response[3],
  575. );
  576. default:
  577. throw new ClientException(
  578. "Received an unknown message type {$response[0]} inside of a pubsub context"
  579. );
  580. }
  581. }
  582. }
  583. /* -------------------------------------------------------------------------- */
  584. abstract class PredisException extends \Exception {
  585. // Base Predis exception class
  586. }
  587. class ClientException extends PredisException {
  588. // Client-side errors
  589. }
  590. class AbortedMultiExec extends PredisException {
  591. // Aborted MULTI/EXEC transactions
  592. }
  593. class ServerException extends PredisException {
  594. // Server-side errors
  595. public function toResponseError() {
  596. return new ResponseError($this->getMessage());
  597. }
  598. }
  599. class CommunicationException extends PredisException {
  600. // Communication errors
  601. private $_connection;
  602. public function __construct(IConnectionSingle $connection,
  603. $message = null, $code = null) {
  604. $this->_connection = $connection;
  605. parent::__construct($message, $code);
  606. }
  607. public function getConnection() { return $this->_connection; }
  608. public function shouldResetConnection() { return true; }
  609. }
  610. class MalformedServerResponse extends CommunicationException {
  611. // Unexpected responses
  612. }
  613. /* -------------------------------------------------------------------------- */
  614. interface ICommand {
  615. public function getCommandId();
  616. public function canBeHashed();
  617. public function closesConnection();
  618. public function getHash(IDistributionStrategy $distributor);
  619. public function setArgumentsArray(Array $arguments);
  620. public function getArguments();
  621. public function parseResponse($data);
  622. }
  623. abstract class Command implements ICommand {
  624. private $_hash;
  625. private $_arguments = array();
  626. public function canBeHashed() {
  627. return true;
  628. }
  629. public function getHash(IDistributionStrategy $distributor) {
  630. if (isset($this->_hash)) {
  631. return $this->_hash;
  632. }
  633. if (isset($this->_arguments[0])) {
  634. // TODO: should we throw an exception if the command does not
  635. // support sharding?
  636. $key = $this->_arguments[0];
  637. $start = strpos($key, '{');
  638. if ($start !== false) {
  639. $end = strpos($key, '}', $start);
  640. if ($end !== false) {
  641. $key = substr($key, ++$start, $end - $start);
  642. }
  643. }
  644. $this->_hash = $distributor->generateKey($key);
  645. return $this->_hash;
  646. }
  647. return null;
  648. }
  649. public function closesConnection() {
  650. return false;
  651. }
  652. protected function filterArguments(Array $arguments) {
  653. return $arguments;
  654. }
  655. public function setArguments(/* arguments */) {
  656. $this->_arguments = $this->filterArguments(func_get_args());
  657. unset($this->_hash);
  658. }
  659. public function setArgumentsArray(Array $arguments) {
  660. $this->_arguments = $this->filterArguments($arguments);
  661. unset($this->_hash);
  662. }
  663. public function getArguments() {
  664. return $this->_arguments;
  665. }
  666. public function getArgument($index = 0) {
  667. if (isset($this->_arguments[$index]) === true) {
  668. return $this->_arguments[$index];
  669. }
  670. }
  671. public function parseResponse($data) {
  672. return $data;
  673. }
  674. }
  675. class ResponseError {
  676. private $_message;
  677. public function __construct($message) {
  678. $this->_message = $message;
  679. }
  680. public function __get($property) {
  681. if ($property == 'error') {
  682. return true;
  683. }
  684. if ($property == 'message') {
  685. return $this->_message;
  686. }
  687. }
  688. public function __isset($property) {
  689. return $property === 'error';
  690. }
  691. public function __toString() {
  692. return $this->_message;
  693. }
  694. }
  695. class ResponseQueued {
  696. public $queued = true;
  697. public function __toString() {
  698. return TextProtocol::QUEUED;
  699. }
  700. }
  701. final class ConnectionFactory {
  702. private static $_registeredSchemes;
  703. private function __construct() {
  704. // NOOP
  705. }
  706. private static function ensureInitialized() {
  707. if (!isset(self::$_registeredSchemes)) {
  708. self::$_registeredSchemes = self::getDefaultSchemes();
  709. }
  710. }
  711. private static function getDefaultSchemes() {
  712. return array(
  713. 'tcp' => '\Predis\Network\TcpConnection',
  714. 'unix' => '\Predis\Network\UnixDomainSocketConnection',
  715. // Compatibility with older versions.
  716. 'redis' => '\Predis\Network\TcpConnection',
  717. );
  718. }
  719. public static function registerScheme($scheme, $connectionClass) {
  720. self::ensureInitialized();
  721. $connectionReflection = new \ReflectionClass($connectionClass);
  722. if (!$connectionReflection->isSubclassOf('\Predis\Network\IConnectionSingle')) {
  723. throw new ClientException(
  724. "Cannot register '$connectionClass' as it is not a valid connection class"
  725. );
  726. }
  727. self::$_registeredSchemes[$scheme] = $connectionClass;
  728. }
  729. public static function create(ConnectionParameters $parameters, IRedisProtocol $protocol = null) {
  730. self::ensureInitialized();
  731. if (!isset(self::$_registeredSchemes[$parameters->scheme])) {
  732. throw new ClientException("Unknown connection scheme: {$parameters->scheme}");
  733. }
  734. $connection = self::$_registeredSchemes[$parameters->scheme];
  735. return new $connection($parameters, $protocol);
  736. }
  737. }
  738. class ConnectionParameters {
  739. private $_parameters;
  740. private static $_sharedOptions;
  741. public function __construct($parameters = null) {
  742. $parameters = $parameters ?: array();
  743. $this->_parameters = is_array($parameters)
  744. ? $this->filter($parameters)
  745. : $this->parseURI($parameters);
  746. }
  747. private static function paramsExtractor($params, $kv) {
  748. @list($k, $v) = explode('=', $kv);
  749. $params[$k] = $v;
  750. return $params;
  751. }
  752. private static function getSharedOptions() {
  753. if (isset(self::$_sharedOptions)) {
  754. return self::$_sharedOptions;
  755. }
  756. $optEmpty = new Options\Option();
  757. $optBoolean = new Options\CustomOption(array(
  758. 'validate' => function($value) { return (bool) $value; },
  759. 'default' => function() { return false; },
  760. ));
  761. self::$_sharedOptions = array(
  762. 'scheme' => new Options\CustomOption(array(
  763. 'default' => function() { return 'tcp'; },
  764. )),
  765. 'host' => new Options\CustomOption(array(
  766. 'default' => function() { return '127.0.0.1'; },
  767. )),
  768. 'port' => new Options\CustomOption(array(
  769. 'validate' => function($value) { return (int) $value; },
  770. 'default' => function() { return 6379; },
  771. )),
  772. 'path' => $optEmpty,
  773. 'database' => $optEmpty,
  774. 'password' => $optEmpty,
  775. 'connection_async' => $optBoolean,
  776. 'connection_persistent' => $optBoolean,
  777. 'connection_timeout' => new Options\CustomOption(array(
  778. 'default' => function() { return 5; },
  779. )),
  780. 'read_write_timeout' => $optEmpty,
  781. 'alias' => $optEmpty,
  782. 'weight' => $optEmpty,
  783. );
  784. return self::$_sharedOptions;
  785. }
  786. protected function parseURI($uri) {
  787. if (stripos($uri, 'unix') === 0) {
  788. // Hack to support URIs for UNIX sockets with minimal effort
  789. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
  790. }
  791. $parsed = @parse_url($uri);
  792. if ($parsed == false || $parsed['host'] == null) {
  793. throw new ClientException("Invalid URI: $uri");
  794. }
  795. if (array_key_exists('query', $parsed)) {
  796. $query = explode('&', $parsed['query']);
  797. $parsed = array_reduce($query, 'self::paramsExtractor', $parsed);
  798. }
  799. return $this->filter($parsed);
  800. }
  801. protected function filter($parameters) {
  802. $handlers = self::getSharedOptions();
  803. foreach ($parameters as $parameter => $value) {
  804. if (isset($handlers[$parameter])) {
  805. $parameters[$parameter] = $handlers[$parameter]($value);
  806. }
  807. }
  808. return $parameters;
  809. }
  810. private function tryInitializeValue($parameter) {
  811. if (isset(self::$_sharedOptions[$parameter])) {
  812. $value = self::$_sharedOptions[$parameter]->getDefault();
  813. $this->_parameters[$parameter] = $value;
  814. return $value;
  815. }
  816. }
  817. public function __get($parameter) {
  818. if (isset($this->_parameters[$parameter])) {
  819. return $this->_parameters[$parameter];
  820. }
  821. return $this->tryInitializeValue($parameter);
  822. }
  823. public function __isset($parameter) {
  824. if (isset($this->_parameters[$parameter])) {
  825. return true;
  826. }
  827. $value = $this->tryInitializeValue($parameter);
  828. return isset($value);
  829. }
  830. }
  831. class ClientOptions {
  832. private $_handlers, $_options;
  833. private static $_sharedOptions;
  834. public function __construct($options = null) {
  835. $this->initialize($options ?: array());
  836. }
  837. private static function getSharedOptions() {
  838. if (isset(self::$_sharedOptions)) {
  839. return self::$_sharedOptions;
  840. }
  841. self::$_sharedOptions = array(
  842. 'profile' => new Options\ClientProfile(),
  843. 'key_distribution' => new Options\ClientKeyDistribution(),
  844. 'iterable_multibulk' => new Options\ClientIterableMultiBulk(),
  845. 'throw_on_error' => new Options\ClientThrowOnError(),
  846. );
  847. return self::$_sharedOptions;
  848. }
  849. private function initialize($options) {
  850. $this->_handlers = $this->getOptions();
  851. foreach ($options as $option => $value) {
  852. if (isset($this->_handlers[$option])) {
  853. $handler = $this->_handlers[$option];
  854. $this->_options[$option] = $handler($value);
  855. }
  856. }
  857. }
  858. private function getOptions() {
  859. return self::getSharedOptions();
  860. }
  861. protected function defineOption($name, Options\IOption $option) {
  862. $this->_handlers[$name] = $option;
  863. }
  864. public function __get($option) {
  865. if (!isset($this->_options[$option])) {
  866. $handler = $this->_handlers[$option];
  867. $this->_options[$option] = $handler->getDefault();
  868. }
  869. return $this->_options[$option];
  870. }
  871. public function __isset($option) {
  872. return isset(self::$_sharedOptions[$option]);
  873. }
  874. }
  875. class Utils {
  876. public static function isCluster(IConnection $connection) {
  877. return $connection instanceof IConnectionCluster;
  878. }
  879. public static function onCommunicationException(CommunicationException $exception) {
  880. if ($exception->shouldResetConnection()) {
  881. $connection = $exception->getConnection();
  882. if ($connection->isConnected()) {
  883. $connection->disconnect();
  884. }
  885. }
  886. throw $exception;
  887. }
  888. public static function filterArrayArguments(Array $arguments) {
  889. if (count($arguments) === 1 && is_array($arguments[0])) {
  890. return $arguments[0];
  891. }
  892. return $arguments;
  893. }
  894. }
  895. /* -------------------------------------------------------------------------- */
  896. namespace Predis\Options;
  897. use Predis\Profiles\ServerProfile;
  898. use Predis\Profiles\IServerProfile;
  899. interface IOption {
  900. public function validate($value);
  901. public function getDefault();
  902. public function __invoke($value);
  903. }
  904. class Option implements IOption {
  905. public function validate($value) {
  906. return $value;
  907. }
  908. public function getDefault() {
  909. return null;
  910. }
  911. public function __invoke($value) {
  912. return $this->validate($value ?: $this->getDefault());
  913. }
  914. }
  915. class CustomOption extends Option {
  916. private $__validate, $_default;
  917. public function __construct(Array $options) {
  918. $validate = isset($options['validate']) ? $options['validate'] : 'parent::validate';
  919. $default = isset($options['default']) ? $options['default'] : 'parent::getDefault';
  920. if (!is_callable($validate) || !is_callable($default)) {
  921. throw new \InvalidArgumentException("Validate and default must be callable");
  922. }
  923. $this->_validate = $validate;
  924. $this->_default = $default;
  925. }
  926. public function validate($value) {
  927. return call_user_func($this->_validate, $value);
  928. }
  929. public function getDefault() {
  930. return $this->validate(call_user_func($this->_default));
  931. }
  932. public function __invoke($value) {
  933. return $this->validate($value ?: $this->getDefault());
  934. }
  935. }
  936. class ClientProfile extends Option {
  937. public function validate($value) {
  938. if ($value instanceof IServerProfile) {
  939. return $value;
  940. }
  941. if (is_string($value)) {
  942. return ServerProfile::get($value);
  943. }
  944. throw new \InvalidArgumentException(
  945. "Invalid value for the profile option"
  946. );
  947. }
  948. public function getDefault() {
  949. return ServerProfile::getDefault();
  950. }
  951. }
  952. class ClientKeyDistribution extends Option {
  953. public function validate($value) {
  954. if ($value instanceof \Predis\Distribution\IDistributionStrategy) {
  955. return $value;
  956. }
  957. if (is_string($value)) {
  958. $valueReflection = new \ReflectionClass($value);
  959. if ($valueReflection->isSubclassOf('\Predis\Distribution\IDistributionStrategy')) {
  960. return new $value;
  961. }
  962. }
  963. throw new \InvalidArgumentException("Invalid value for key distribution");
  964. }
  965. public function getDefault() {
  966. return new \Predis\Distribution\HashRing();
  967. }
  968. }
  969. class ClientIterableMultiBulk extends Option {
  970. public function validate($value) {
  971. return (bool) $value;
  972. }
  973. public function getDefault() {
  974. return false;
  975. }
  976. }
  977. class ClientThrowOnError extends Option {
  978. public function validate($value) {
  979. return (bool) $value;
  980. }
  981. public function getDefault() {
  982. return true;
  983. }
  984. }
  985. /* -------------------------------------------------------------------------- */
  986. namespace Predis\Network;
  987. use Predis\Utils;
  988. use Predis\ICommand;
  989. use Predis\ConnectionParameters;
  990. use Predis\CommunicationException;
  991. use Predis\Protocols\IRedisProtocol;
  992. use Predis\Protocols\TextProtocol;
  993. use Predis\Distribution\IDistributionStrategy;
  994. interface IConnection {
  995. public function connect();
  996. public function disconnect();
  997. public function isConnected();
  998. public function writeCommand(ICommand $command);
  999. public function readResponse(ICommand $command);
  1000. public function executeCommand(ICommand $command);
  1001. }
  1002. interface IConnectionSingle extends IConnection {
  1003. public function getParameters();
  1004. public function getProtocol();
  1005. public function __toString();
  1006. public function writeBytes($buffer);
  1007. public function readBytes($length);
  1008. public function readLine();
  1009. public function pushInitCommand(ICommand $command);
  1010. }
  1011. interface IConnectionCluster extends IConnection {
  1012. public function getConnection(ICommand $command);
  1013. public function getConnectionById($connectionId);
  1014. }
  1015. abstract class ConnectionBase implements IConnectionSingle {
  1016. protected $_params, $_socket, $_initCmds, $_protocol;
  1017. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol) {
  1018. $this->_initCmds = array();
  1019. $this->_params = $parameters;
  1020. $this->_protocol = $protocol;
  1021. }
  1022. public function __destruct() {
  1023. $this->disconnect();
  1024. }
  1025. public function isConnected() {
  1026. return is_resource($this->_socket);
  1027. }
  1028. protected abstract function createResource();
  1029. public function connect() {
  1030. if ($this->isConnected()) {
  1031. throw new ClientException('Connection already estabilished');
  1032. }
  1033. $this->createResource();
  1034. }
  1035. public function disconnect() {
  1036. if ($this->isConnected()) {
  1037. fclose($this->_socket);
  1038. }
  1039. }
  1040. public function pushInitCommand(ICommand $command){
  1041. $this->_initCmds[] = $command;
  1042. }
  1043. public function executeCommand(ICommand $command) {
  1044. $this->writeCommand($command);
  1045. if ($command->closesConnection()) {
  1046. return $this->disconnect();
  1047. }
  1048. return $this->readResponse($command);
  1049. }
  1050. protected function onCommunicationException($message, $code = null) {
  1051. Utils::onCommunicationException(
  1052. new CommunicationException($this, $message, $code)
  1053. );
  1054. }
  1055. public function getResource() {
  1056. if (!$this->isConnected()) {
  1057. $this->connect();
  1058. }
  1059. return $this->_socket;
  1060. }
  1061. public function getParameters() {
  1062. return $this->_params;
  1063. }
  1064. public function getProtocol() {
  1065. return $this->_protocol;
  1066. }
  1067. public function __toString() {
  1068. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  1069. }
  1070. }
  1071. class TcpConnection extends ConnectionBase implements IConnectionSingle {
  1072. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol = null) {
  1073. parent::__construct($this->checkParameters($parameters), $protocol ?: new TextProtocol());
  1074. }
  1075. public function __destruct() {
  1076. if (!$this->_params->connection_persistent) {
  1077. $this->disconnect();
  1078. }
  1079. }
  1080. protected function checkParameters(ConnectionParameters $parameters) {
  1081. if ($parameters->scheme != 'tcp' && $parameters->scheme != 'redis') {
  1082. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  1083. }
  1084. return $parameters;
  1085. }
  1086. protected function createResource() {
  1087. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  1088. $connectFlags = STREAM_CLIENT_CONNECT;
  1089. if ($this->_params->connection_async) {
  1090. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  1091. }
  1092. if ($this->_params->connection_persistent) {
  1093. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1094. }
  1095. $this->_socket = @stream_socket_client(
  1096. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1097. );
  1098. if (!$this->_socket) {
  1099. $this->onCommunicationException(trim($errstr), $errno);
  1100. }
  1101. if (isset($this->_params->read_write_timeout)) {
  1102. $timeoutSeconds = floor($this->_params->read_write_timeout);
  1103. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  1104. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  1105. }
  1106. }
  1107. private function sendInitializationCommands() {
  1108. foreach ($this->_initCmds as $command) {
  1109. $this->writeCommand($command);
  1110. }
  1111. foreach ($this->_initCmds as $command) {
  1112. $this->readResponse($command);
  1113. }
  1114. }
  1115. public function connect() {
  1116. parent::connect();
  1117. if (count($this->_initCmds) > 0){
  1118. $this->sendInitializationCommands();
  1119. }
  1120. }
  1121. public function writeCommand(ICommand $command) {
  1122. $this->_protocol->write($this, $command);
  1123. }
  1124. public function readResponse(ICommand $command) {
  1125. $response = $this->_protocol->read($this);
  1126. $skipparse = isset($response->queued) || isset($response->error);
  1127. return $skipparse ? $response : $command->parseResponse($response);
  1128. }
  1129. public function rawCommand($buffer) {
  1130. $this->writeBytes($buffer);
  1131. return $this->_protocol->read($this);
  1132. }
  1133. public function writeBytes($value) {
  1134. $socket = $this->getResource();
  1135. while (($length = strlen($value)) > 0) {
  1136. $written = fwrite($socket, $value);
  1137. if ($length === $written) {
  1138. return true;
  1139. }
  1140. if ($written === false || $written === 0) {
  1141. $this->onCommunicationException('Error while writing bytes to the server');
  1142. }
  1143. $value = substr($value, $written);
  1144. }
  1145. return true;
  1146. }
  1147. public function readBytes($length) {
  1148. if ($length <= 0) {
  1149. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  1150. }
  1151. $socket = $this->getResource();
  1152. $value = '';
  1153. do {
  1154. $chunk = fread($socket, $length);
  1155. if ($chunk === false || $chunk === '') {
  1156. $this->onCommunicationException('Error while reading bytes from the server');
  1157. }
  1158. $value .= $chunk;
  1159. }
  1160. while (($length -= strlen($chunk)) > 0);
  1161. return $value;
  1162. }
  1163. public function readLine() {
  1164. $socket = $this->getResource();
  1165. $value = '';
  1166. do {
  1167. $chunk = fgets($socket);
  1168. if ($chunk === false || $chunk === '') {
  1169. $this->onCommunicationException('Error while reading line from the server');
  1170. }
  1171. $value .= $chunk;
  1172. }
  1173. while (substr($value, -2) !== TextProtocol::NEWLINE);
  1174. return substr($value, 0, -2);
  1175. }
  1176. }
  1177. class UnixDomainSocketConnection extends TcpConnection {
  1178. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol = null) {
  1179. parent::__construct($this->checkParameters($parameters), $protocol);
  1180. }
  1181. protected function checkParameters(ConnectionParameters $parameters) {
  1182. if ($parameters->scheme != 'unix') {
  1183. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  1184. }
  1185. if (!file_exists($parameters->path)) {
  1186. throw new \InvalidArgumentException("Could not find {$parameters->path}");
  1187. }
  1188. return $parameters;
  1189. }
  1190. protected function createResource() {
  1191. $uri = sprintf('unix:///%s', $this->_params->path);
  1192. $connectFlags = STREAM_CLIENT_CONNECT;
  1193. if ($this->_params->connection_persistent) {
  1194. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1195. }
  1196. $this->_socket = @stream_socket_client(
  1197. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1198. );
  1199. if (!$this->_socket) {
  1200. $this->onCommunicationException(trim($errstr), $errno);
  1201. }
  1202. }
  1203. }
  1204. class ConnectionCluster implements IConnectionCluster, \IteratorAggregate {
  1205. private $_pool, $_distributor;
  1206. public function __construct(IDistributionStrategy $distributor = null) {
  1207. $this->_pool = array();
  1208. $this->_distributor = $distributor ?: new Distribution\HashRing();
  1209. }
  1210. public function isConnected() {
  1211. foreach ($this->_pool as $connection) {
  1212. if ($connection->isConnected()) {
  1213. return true;
  1214. }
  1215. }
  1216. return false;
  1217. }
  1218. public function connect() {
  1219. foreach ($this->_pool as $connection) {
  1220. $connection->connect();
  1221. }
  1222. }
  1223. public function disconnect() {
  1224. foreach ($this->_pool as $connection) {
  1225. $connection->disconnect();
  1226. }
  1227. }
  1228. public function add(IConnectionSingle $connection) {
  1229. $parameters = $connection->getParameters();
  1230. if (isset($parameters->alias)) {
  1231. $this->_pool[$parameters->alias] = $connection;
  1232. }
  1233. else {
  1234. $this->_pool[] = $connection;
  1235. }
  1236. $this->_distributor->add($connection, $parameters->weight);
  1237. }
  1238. public function getConnection(ICommand $command) {
  1239. if ($command->canBeHashed() === false) {
  1240. throw new ClientException(
  1241. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1242. );
  1243. }
  1244. return $this->_distributor->get($command->getHash($this->_distributor));
  1245. }
  1246. public function getConnectionById($id = null) {
  1247. $alias = $id ?: 0;
  1248. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1249. }
  1250. public function getIterator() {
  1251. return new \ArrayIterator($this->_pool);
  1252. }
  1253. public function writeCommand(ICommand $command) {
  1254. $this->getConnection($command)->writeCommand($command);
  1255. }
  1256. public function readResponse(ICommand $command) {
  1257. return $this->getConnection($command)->readResponse($command);
  1258. }
  1259. public function executeCommand(ICommand $command) {
  1260. $connection = $this->getConnection($command);
  1261. $connection->writeCommand($command);
  1262. return $connection->readResponse($command);
  1263. }
  1264. }
  1265. /* -------------------------------------------------------------------------- */
  1266. namespace Predis\Protocols;
  1267. use Predis\ICommand;
  1268. use Predis\Iterators;
  1269. use Predis\MalformedServerResponse;
  1270. use Predis\Network\IConnectionSingle;
  1271. interface IRedisProtocol {
  1272. public function write(IConnectionSingle $connection, ICommand $command);
  1273. public function read(IConnectionSingle $connection);
  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 IRedisProtocol {
  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. ?>