Predis.php 109 KB

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