Predis.php 112 KB

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