Predis.php 99 KB

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