Predis.php 104 KB

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