Predis.php 98 KB

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