Predis.php 109 KB

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