Predis.php 79 KB

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