Predis.php 108 KB

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