Predis.php 104 KB

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