Predis.php 103 KB

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