Predis.php 99 KB

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