Predis.php 104 KB

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