Predis.php 99 KB

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