Predis.php 104 KB

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