Predis.php 83 KB

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