Predis.php 97 KB

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