Predis.php 109 KB

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