Predis.php 100 KB

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