Predis.php 99 KB

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