Predis.php 77 KB

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