Predis.php 72 KB

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