Predis.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { }
  5. class ServerException extends PredisException { }
  6. class MalformedServerResponse extends ServerException { }
  7. /* ------------------------------------------------------------------------- */
  8. class Client {
  9. private $_connection, $_serverProfile;
  10. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  11. $this->setProfile($serverProfile ?: RedisServerProfile::getDefault());
  12. $this->setupConnection($parameters);
  13. }
  14. public function __destruct() {
  15. $this->_connection->disconnect();
  16. }
  17. public static function create(/* arguments */) {
  18. $argv = func_get_args();
  19. $argc = func_num_args();
  20. $serverProfile = null;
  21. $lastArg = $argv[$argc-1];
  22. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  23. $serverProfile = array_pop($argv);
  24. $argc--;
  25. }
  26. if ($argc === 0) {
  27. throw new ClientException('Missing connection parameters');
  28. }
  29. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  30. }
  31. private function setupConnection($parameters) {
  32. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  33. throw new ClientException('Invalid parameters type (array or string expected)');
  34. }
  35. if (is_array($parameters) && isset($parameters[0])) {
  36. $cluster = new ConnectionCluster();
  37. foreach ($parameters as $shardParams) {
  38. $cluster->add($this->createConnection($shardParams));
  39. }
  40. $this->setConnection($cluster);
  41. }
  42. else {
  43. $this->setConnection($this->createConnection($parameters));
  44. }
  45. }
  46. private function createConnection($parameters) {
  47. $params = new ConnectionParameters($parameters);
  48. $connection = new Connection($params);
  49. if ($params->password !== null) {
  50. $connection->pushInitCommand($this->createCommand(
  51. 'auth', array($params->password)
  52. ));
  53. }
  54. if ($params->database !== null) {
  55. $connection->pushInitCommand($this->createCommand(
  56. 'select', array($params->database)
  57. ));
  58. }
  59. return $connection;
  60. }
  61. private function setConnection(IConnection $connection) {
  62. $this->_connection = $connection;
  63. }
  64. public function setProfile(RedisServerProfile $serverProfile) {
  65. $this->_serverProfile = $serverProfile;
  66. }
  67. public function getProfile() {
  68. return $this->_serverProfile;
  69. }
  70. public function connect() {
  71. $this->_connection->connect();
  72. }
  73. public function disconnect() {
  74. $this->_connection->disconnect();
  75. }
  76. public function isConnected() {
  77. return $this->_connection->isConnected();
  78. }
  79. public function getConnection($id = null) {
  80. if (!isset($id)) {
  81. return $this->_connection;
  82. }
  83. else {
  84. return $this->_connection instanceof ConnectionCluster
  85. ? $this->_connection->getConnectionById($id)
  86. : $this->_connection;
  87. }
  88. }
  89. public function __call($method, $arguments) {
  90. $command = $this->_serverProfile->createCommand($method, $arguments);
  91. return $this->executeCommand($command);
  92. }
  93. public function createCommand($method, $arguments = array()) {
  94. return $this->_serverProfile->createCommand($method, $arguments);
  95. }
  96. private function executeCommandInternal(IConnection $connection, Command $command) {
  97. $connection->writeCommand($command);
  98. if ($command->closesConnection()) {
  99. return $connection->disconnect();
  100. }
  101. return $connection->readResponse($command);
  102. }
  103. public function executeCommand(Command $command) {
  104. return self::executeCommandInternal($this->_connection, $command);
  105. }
  106. public function executeCommandOnShards(Command $command) {
  107. $replies = array();
  108. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  109. foreach($this->_connection as $connection) {
  110. $replies[] = self::executeCommandInternal($connection, $command);
  111. }
  112. }
  113. else {
  114. $replies[] = self::executeCommandInternal($this->_connection, $command);
  115. }
  116. return $replies;
  117. }
  118. public function rawCommand($rawCommandData, $closesConnection = false) {
  119. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  120. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  121. }
  122. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  123. }
  124. public function pipeline($pipelineBlock = null) {
  125. $pipeline = new CommandPipeline($this);
  126. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  127. }
  128. public function multiExec($multiExecBlock = null) {
  129. $multiExec = new MultiExecBlock($this);
  130. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  131. }
  132. }
  133. /* ------------------------------------------------------------------------- */
  134. abstract class Command {
  135. private $_arguments, $_hash;
  136. public abstract function getCommandId();
  137. public abstract function serializeRequest($command, $arguments);
  138. public function canBeHashed() {
  139. return true;
  140. }
  141. public function getHash() {
  142. if (isset($this->_hash)) {
  143. return $this->_hash;
  144. }
  145. else {
  146. if (isset($this->_arguments[0])) {
  147. $key = $this->_arguments[0];
  148. $start = strpos($key, '{');
  149. $end = strpos($key, '}');
  150. if ($start !== false && $end !== false) {
  151. $key = substr($key, ++$start, $end - $start);
  152. }
  153. $this->_hash = crc32($key);
  154. return $this->_hash;
  155. }
  156. }
  157. return null;
  158. }
  159. public function closesConnection() {
  160. return false;
  161. }
  162. protected function filterArguments(Array $arguments) {
  163. return $arguments;
  164. }
  165. public function setArguments(/* arguments */) {
  166. $this->_arguments = $this->filterArguments(func_get_args());
  167. }
  168. public function setArgumentsArray(Array $arguments) {
  169. $this->_arguments = $this->filterArguments($arguments);
  170. }
  171. protected function getArguments() {
  172. return isset($this->_arguments) ? $this->_arguments : array();
  173. }
  174. public function getArgument($index = 0) {
  175. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  176. }
  177. public function parseResponse($data) {
  178. return $data;
  179. }
  180. public final function __invoke() {
  181. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  182. }
  183. }
  184. abstract class InlineCommand extends Command {
  185. public function serializeRequest($command, $arguments) {
  186. if (isset($arguments[0]) && is_array($arguments[0])) {
  187. $arguments[0] = implode($arguments[0], ' ');
  188. }
  189. return $command . ' ' . implode($arguments, ' ') . Response::NEWLINE;
  190. }
  191. }
  192. abstract class BulkCommand extends Command {
  193. public function serializeRequest($command, $arguments) {
  194. $data = array_pop($arguments);
  195. if (is_array($data)) {
  196. $data = implode($data, ' ');
  197. }
  198. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  199. Response::NEWLINE . $data . Response::NEWLINE;
  200. }
  201. }
  202. abstract class MultiBulkCommand extends Command {
  203. public function serializeRequest($command, $arguments) {
  204. $buffer = array();
  205. $cmd_args = null;
  206. if (count($arguments) === 1 && is_array($arguments[0])) {
  207. $cmd_args = array();
  208. foreach ($arguments[0] as $k => $v) {
  209. $cmd_args[] = $k;
  210. $cmd_args[] = $v;
  211. }
  212. }
  213. else {
  214. $cmd_args = $arguments;
  215. }
  216. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Response::NEWLINE;
  217. $buffer[] = '$' . strlen($command) . Response::NEWLINE . $command . Response::NEWLINE;
  218. foreach ($cmd_args as $argument) {
  219. $buffer[] = '$' . strlen($argument) . Response::NEWLINE . $argument . Response::NEWLINE;
  220. }
  221. return implode('', $buffer);
  222. }
  223. }
  224. /* ------------------------------------------------------------------------- */
  225. interface IResponseHandler {
  226. function handle($socket, $prefix, $payload);
  227. }
  228. class ResponseStatusHandler implements IResponseHandler {
  229. public function handle($socket, $prefix, $status) {
  230. if ($status === Response::OK) {
  231. return true;
  232. }
  233. else if ($status === Response::QUEUED) {
  234. return new ResponseQueued();
  235. }
  236. return $status;
  237. }
  238. }
  239. class ResponseErrorHandler implements IResponseHandler {
  240. public function handle($socket, $prefix, $errorMessage) {
  241. throw new ServerException(substr($errorMessage, 4));
  242. }
  243. }
  244. class ResponseBulkHandler implements IResponseHandler {
  245. public function handle($socket, $prefix, $dataLength) {
  246. if (!is_numeric($dataLength)) {
  247. throw new ClientException("Cannot parse '$dataLength' as data length");
  248. }
  249. if ($dataLength > 0) {
  250. $value = stream_get_contents($socket, $dataLength);
  251. if ($value === false) {
  252. throw new ClientException('An error has occurred while reading from the network stream');
  253. }
  254. fread($socket, 2);
  255. return $value;
  256. }
  257. else if ($dataLength == 0) {
  258. fread($socket, 2);
  259. return '';
  260. }
  261. return null;
  262. }
  263. }
  264. class ResponseMultiBulkHandler implements IResponseHandler {
  265. public function handle($socket, $prefix, $rawLength) {
  266. if (!is_numeric($rawLength)) {
  267. throw new ClientException("Cannot parse '$rawLength' as data length");
  268. }
  269. $listLength = (int) $rawLength;
  270. if ($listLength === -1) {
  271. return null;
  272. }
  273. $list = array();
  274. if ($listLength > 0) {
  275. for ($i = 0; $i < $listLength; $i++) {
  276. $list[] = Response::read($socket);
  277. }
  278. }
  279. return $list;
  280. }
  281. }
  282. class ResponseIntegerHandler implements IResponseHandler {
  283. public function handle($socket, $prefix, $number) {
  284. if (is_numeric($number)) {
  285. return (int) $number;
  286. }
  287. else {
  288. if ($number !== Response::NULL) {
  289. throw new ClientException("Cannot parse '$number' as numeric response");
  290. }
  291. return null;
  292. }
  293. }
  294. }
  295. class Response {
  296. const NEWLINE = "\r\n";
  297. const OK = 'OK';
  298. const ERROR = 'ERR';
  299. const QUEUED = 'QUEUED';
  300. const NULL = 'nil';
  301. private static $_prefixHandlers;
  302. private static function initializePrefixHandlers() {
  303. return array(
  304. '+' => new ResponseStatusHandler(),
  305. '-' => new ResponseErrorHandler(),
  306. ':' => new ResponseIntegerHandler(),
  307. '$' => new ResponseBulkHandler(),
  308. '*' => new ResponseMultiBulkHandler()
  309. );
  310. }
  311. public static function read($socket) {
  312. $header = fgets($socket);
  313. if ($header === false) {
  314. throw new ClientException('An error has occurred while reading from the network stream');
  315. }
  316. $prefix = $header[0];
  317. $payload = substr($header, 1, -2);
  318. if (!isset(self::$_prefixHandlers)) {
  319. self::$_prefixHandlers = self::initializePrefixHandlers();
  320. }
  321. if (!isset(self::$_prefixHandlers[$prefix])) {
  322. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  323. }
  324. $handler = self::$_prefixHandlers[$prefix];
  325. return $handler->handle($socket, $prefix, $payload);
  326. }
  327. }
  328. class ResponseQueued {
  329. public $queued = true;
  330. public function __toString() {
  331. return Response::QUEUED;
  332. }
  333. }
  334. /* ------------------------------------------------------------------------- */
  335. class CommandPipeline {
  336. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  337. public function __construct(Client $redisClient) {
  338. $this->_redisClient = $redisClient;
  339. $this->_pipelineBuffer = array();
  340. $this->_returnValues = array();
  341. }
  342. public function __call($method, $arguments) {
  343. $command = $this->_redisClient->createCommand($method, $arguments);
  344. $this->recordCommand($command);
  345. return $this;
  346. }
  347. private function recordCommand(Command $command) {
  348. $this->_pipelineBuffer[] = $command;
  349. }
  350. private function getRecordedCommands() {
  351. return $this->_pipelineBuffer;
  352. }
  353. public function flushPipeline() {
  354. $sizeofPipe = count($this->_pipelineBuffer);
  355. if ($sizeofPipe === 0) {
  356. return;
  357. }
  358. $connection = $this->_redisClient->getConnection();
  359. $commands = &$this->_pipelineBuffer;
  360. foreach ($commands as $command) {
  361. $connection->writeCommand($command);
  362. }
  363. for ($i = 0; $i < $sizeofPipe; $i++) {
  364. $this->_returnValues[] = $connection->readResponse($commands[$i]);
  365. unset($commands[$i]);
  366. }
  367. $this->_pipelineBuffer = array();
  368. return $this;
  369. }
  370. private function setRunning($bool) {
  371. if ($bool == true && $this->_running == true) {
  372. throw new ClientException("This pipeline is already opened");
  373. }
  374. $this->_running = $bool;
  375. }
  376. public function execute($block = null) {
  377. if ($block && !is_callable($block)) {
  378. throw new \RuntimeException('Argument passed must be a callable object');
  379. }
  380. $this->setRunning(true);
  381. $pipelineBlockException = null;
  382. try {
  383. if ($block !== null) {
  384. $block($this);
  385. }
  386. $this->flushPipeline();
  387. }
  388. catch (\Exception $exception) {
  389. $pipelineBlockException = $exception;
  390. }
  391. $this->setRunning(false);
  392. if ($pipelineBlockException !== null) {
  393. throw $pipelineBlockException;
  394. }
  395. return $this->_returnValues;
  396. }
  397. }
  398. class MultiExecBlock {
  399. private $_redisClient, $_commands, $_initialized;
  400. public function __construct(Client $redisClient) {
  401. $this->_initialized = false;
  402. $this->_redisClient = $redisClient;
  403. $this->_commands = array();
  404. }
  405. private function initialize() {
  406. if ($this->_initialized === false) {
  407. $this->_redisClient->multi();
  408. $this->_initialized = true;
  409. }
  410. }
  411. public function __call($method, $arguments) {
  412. $this->initialize();
  413. $command = $this->_redisClient->createCommand($method, $arguments);
  414. $response = $this->_redisClient->executeCommand($command);
  415. if (isset($response->queued)) {
  416. $this->_commands[] = $command;
  417. return $this;
  418. }
  419. else {
  420. throw new ClientException('The server did not respond with a QUEUED status reply');
  421. }
  422. }
  423. public function execute($block = null) {
  424. if ($block && !is_callable($block)) {
  425. throw new \RuntimeException('Argument passed must be a callable object');
  426. }
  427. $blockException = null;
  428. $returnValues = array();
  429. try {
  430. if ($block !== null) {
  431. $block($this);
  432. }
  433. $execReply = $this->_redisClient->exec();
  434. $commands = &$this->_commands;
  435. $sizeofReplies = count($execReply);
  436. if ($sizeofReplies !== count($commands)) {
  437. // TODO: think of a better exception message
  438. throw new ClientException("Out-of-sync");
  439. }
  440. for ($i = 0; $i < $sizeofReplies; $i++) {
  441. $returnValues[] = $commands[$i]->parseResponse($execReply[$i]);
  442. unset($commands[$i]);
  443. }
  444. }
  445. catch (\Exception $exception) {
  446. $blockException = $exception;
  447. }
  448. if ($blockException !== null) {
  449. throw $blockException;
  450. }
  451. return $returnValues;
  452. }
  453. }
  454. /* ------------------------------------------------------------------------- */
  455. class ConnectionParameters {
  456. const DEFAULT_HOST = '127.0.0.1';
  457. const DEFAULT_PORT = 6379;
  458. const DEFAULT_TIMEOUT = 5;
  459. private $_parameters;
  460. public function __construct($parameters) {
  461. $parameters = $parameters ?: array();
  462. $this->_parameters = is_array($parameters)
  463. ? self::filterConnectionParams($parameters)
  464. : self::parseURI($parameters);
  465. }
  466. private static function parseURI($uri) {
  467. $parsed = @parse_url($uri);
  468. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  469. throw new ClientException("Invalid URI: $uri");
  470. }
  471. if (array_key_exists('query', $parsed)) {
  472. $details = array();
  473. foreach (explode('&', $parsed['query']) as $kv) {
  474. list($k, $v) = explode('=', $kv);
  475. switch ($k) {
  476. case 'database':
  477. $details['database'] = $v;
  478. break;
  479. case 'password':
  480. $details['password'] = $v;
  481. break;
  482. case 'connection_timeout':
  483. $details['connection_timeout'] = $v;
  484. break;
  485. case 'read_write_timeout':
  486. $details['read_write_timeout'] = $v;
  487. break;
  488. case 'alias':
  489. $details['alias'] = $v;
  490. break;
  491. }
  492. }
  493. $parsed = array_merge($parsed, $details);
  494. }
  495. return self::filterConnectionParams($parsed);
  496. }
  497. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  498. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  499. }
  500. private static function filterConnectionParams($parameters) {
  501. return array(
  502. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  503. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  504. 'database' => self::getParamOrDefault($parameters, 'database'),
  505. 'password' => self::getParamOrDefault($parameters, 'password'),
  506. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  507. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  508. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  509. );
  510. }
  511. public function __get($parameter) {
  512. return $this->_parameters[$parameter];
  513. }
  514. public function __isset($parameter) {
  515. return isset($this->_parameters[$parameter]);
  516. }
  517. }
  518. interface IConnection {
  519. public function connect();
  520. public function disconnect();
  521. public function isConnected();
  522. public function writeCommand(Command $command);
  523. public function readResponse(Command $command);
  524. }
  525. class Connection implements IConnection {
  526. private $_params, $_socket, $_initCmds;
  527. public function __construct(ConnectionParameters $parameters) {
  528. $this->_params = $parameters;
  529. $this->_initCmds = array();
  530. }
  531. public function __destruct() {
  532. $this->disconnect();
  533. }
  534. public function isConnected() {
  535. return is_resource($this->_socket);
  536. }
  537. public function connect() {
  538. if ($this->isConnected()) {
  539. throw new ClientException('Connection already estabilished');
  540. }
  541. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  542. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $this->_params->connection_timeout);
  543. if (!$this->_socket) {
  544. throw new ClientException(trim($errstr), $errno);
  545. }
  546. if (isset($this->_params->read_write_timeout)) {
  547. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  548. }
  549. if (count($this->_initCmds) > 0){
  550. $this->sendInitializationCommands();
  551. }
  552. }
  553. public function disconnect() {
  554. if ($this->isConnected()) {
  555. fclose($this->_socket);
  556. }
  557. }
  558. public function pushInitCommand(Command $command){
  559. $this->_initCmds[] = $command;
  560. }
  561. private function sendInitializationCommands() {
  562. foreach ($this->_initCmds as $command) {
  563. $this->writeCommand($command);
  564. }
  565. foreach ($this->_initCmds as $command) {
  566. $this->readResponse($command);
  567. }
  568. }
  569. public function writeCommand(Command $command) {
  570. $written = fwrite($this->getSocket(), $command());
  571. if ($written === false){
  572. throw new ClientException(sprintf(
  573. 'An error has occurred while writing command %s on the network stream'),
  574. $command->getCommandId()
  575. );
  576. }
  577. }
  578. public function readResponse(Command $command) {
  579. $response = Response::read($this->getSocket());
  580. return isset($response->queued) ? $response : $command->parseResponse($response);
  581. }
  582. public function rawCommand($rawCommandData, $closesConnection = false) {
  583. $socket = $this->getSocket();
  584. $written = fwrite($socket, $rawCommandData);
  585. if ($written === false){
  586. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  587. }
  588. if ($closesConnection) {
  589. return;
  590. }
  591. return Response::read($socket);
  592. }
  593. public function getSocket() {
  594. if (!$this->isConnected()) {
  595. $this->connect();
  596. }
  597. return $this->_socket;
  598. }
  599. public function getAlias() {
  600. return $this->_params->alias;
  601. }
  602. public function __toString() {
  603. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  604. }
  605. }
  606. class ConnectionCluster implements IConnection, \IteratorAggregate {
  607. // TODO: find a clean way to handle connection failures of single nodes.
  608. private $_pool, $_ring;
  609. public function __construct() {
  610. $this->_pool = array();
  611. $this->_ring = new Utilities\HashRing();
  612. }
  613. public function __destruct() {
  614. $this->disconnect();
  615. }
  616. public function isConnected() {
  617. foreach ($this->_pool as $connection) {
  618. if ($connection->isConnected()) {
  619. return true;
  620. }
  621. }
  622. return false;
  623. }
  624. public function connect() {
  625. foreach ($this->_pool as $connection) {
  626. $connection->connect();
  627. }
  628. }
  629. public function disconnect() {
  630. foreach ($this->_pool as $connection) {
  631. $connection->disconnect();
  632. }
  633. }
  634. public function add(Connection $connection) {
  635. $connectionAlias = $connection->getAlias();
  636. if (isset($connectionAlias)) {
  637. $this->_pool[$connectionAlias] = $connection;
  638. }
  639. else {
  640. $this->_pool[] = $connection;
  641. }
  642. $this->_ring->add($connection);
  643. }
  644. private function getConnection(Command $command) {
  645. if ($command->canBeHashed() === false) {
  646. throw new ClientException(
  647. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  648. );
  649. }
  650. return $this->_ring->get($command->getHash());
  651. }
  652. public function getConnectionById($id = null) {
  653. return $this->_pool[$id ?: 0];
  654. }
  655. public function getIterator() {
  656. return new \ArrayIterator($this->_pool);
  657. }
  658. public function writeCommand(Command $command) {
  659. $this->getConnection($command)->writeCommand($command);
  660. }
  661. public function readResponse(Command $command) {
  662. return $this->getConnection($command)->readResponse($command);
  663. }
  664. }
  665. /* ------------------------------------------------------------------------- */
  666. abstract class RedisServerProfile {
  667. private static $_serverProfiles;
  668. private $_registeredCommands;
  669. public function __construct() {
  670. $this->_registeredCommands = $this->getSupportedCommands();
  671. }
  672. public abstract function getVersion();
  673. protected abstract function getSupportedCommands();
  674. public static function getDefault() {
  675. return self::get('default');
  676. }
  677. private static function predisServerProfiles() {
  678. return array(
  679. '1.0' => '\Predis\RedisServer_v1_0',
  680. '1.2' => '\Predis\RedisServer_v1_2',
  681. 'default' => '\Predis\RedisServer_v1_2',
  682. 'dev' => '\Predis\RedisServer_vNext',
  683. );
  684. }
  685. public static function get($version) {
  686. if (!isset(self::$_serverProfiles)) {
  687. self::$_serverProfiles = self::predisServerProfiles();
  688. }
  689. if (!isset(self::$_serverProfiles[$version])) {
  690. throw new ClientException("Unknown server profile: $version");
  691. }
  692. $profile = self::$_serverProfiles[$version];
  693. return new $profile();
  694. }
  695. public function compareWith($version, $operator = null) {
  696. // one could expect that PHP's version_compare would behave
  697. // the same way if invoked with 2 arguments or 3 arguments
  698. // with the third being NULL, but it is not like that.
  699. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  700. // we might need to revise the behavior of this method.
  701. return ($operator === null
  702. ? version_compare($this, $version)
  703. : version_compare($this, $version, $operator)
  704. );
  705. }
  706. public function supportsCommand($command) {
  707. return isset($this->_registeredCommands[$command]);
  708. }
  709. public function createCommand($method, $arguments = array()) {
  710. if (!isset($this->_registeredCommands[$method])) {
  711. throw new ClientException("'$method' is not a registered Redis command");
  712. }
  713. $commandClass = $this->_registeredCommands[$method];
  714. $command = new $commandClass();
  715. $command->setArgumentsArray($arguments);
  716. return $command;
  717. }
  718. public function registerCommands(Array $commands) {
  719. foreach ($commands as $command => $aliases) {
  720. $this->registerCommand($command, $aliases);
  721. }
  722. }
  723. public function registerCommand($command, $aliases) {
  724. $commandReflection = new \ReflectionClass($command);
  725. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  726. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  727. }
  728. if (is_array($aliases)) {
  729. foreach ($aliases as $alias) {
  730. $this->_registeredCommands[$alias] = $command;
  731. }
  732. }
  733. else {
  734. $this->_registeredCommands[$aliases] = $command;
  735. }
  736. }
  737. public function __toString() {
  738. return $this->getVersion();
  739. }
  740. }
  741. class RedisServer_v1_0 extends RedisServerProfile {
  742. public function getVersion() { return '1.0'; }
  743. public function getSupportedCommands() {
  744. return array(
  745. /* miscellaneous commands */
  746. 'ping' => '\Predis\Commands\Ping',
  747. 'echo' => '\Predis\Commands\DoEcho',
  748. 'auth' => '\Predis\Commands\Auth',
  749. /* connection handling */
  750. 'quit' => '\Predis\Commands\Quit',
  751. /* commands operating on string values */
  752. 'set' => '\Predis\Commands\Set',
  753. 'setnx' => '\Predis\Commands\SetPreserve',
  754. 'setPreserve' => '\Predis\Commands\SetPreserve',
  755. 'get' => '\Predis\Commands\Get',
  756. 'mget' => '\Predis\Commands\GetMultiple',
  757. 'getMultiple' => '\Predis\Commands\GetMultiple',
  758. 'getset' => '\Predis\Commands\GetSet',
  759. 'getSet' => '\Predis\Commands\GetSet',
  760. 'incr' => '\Predis\Commands\Increment',
  761. 'increment' => '\Predis\Commands\Increment',
  762. 'incrby' => '\Predis\Commands\IncrementBy',
  763. 'incrementBy' => '\Predis\Commands\IncrementBy',
  764. 'decr' => '\Predis\Commands\Decrement',
  765. 'decrement' => '\Predis\Commands\Decrement',
  766. 'decrby' => '\Predis\Commands\DecrementBy',
  767. 'decrementBy' => '\Predis\Commands\DecrementBy',
  768. 'exists' => '\Predis\Commands\Exists',
  769. 'del' => '\Predis\Commands\Delete',
  770. 'delete' => '\Predis\Commands\Delete',
  771. 'type' => '\Predis\Commands\Type',
  772. /* commands operating on the key space */
  773. 'keys' => '\Predis\Commands\Keys',
  774. 'randomkey' => '\Predis\Commands\RandomKey',
  775. 'randomKey' => '\Predis\Commands\RandomKey',
  776. 'rename' => '\Predis\Commands\Rename',
  777. 'renamenx' => '\Predis\Commands\RenamePreserve',
  778. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  779. 'expire' => '\Predis\Commands\Expire',
  780. 'expireat' => '\Predis\Commands\ExpireAt',
  781. 'expireAt' => '\Predis\Commands\ExpireAt',
  782. 'dbsize' => '\Predis\Commands\DatabaseSize',
  783. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  784. 'ttl' => '\Predis\Commands\TimeToLive',
  785. 'timeToLive' => '\Predis\Commands\TimeToLive',
  786. /* commands operating on lists */
  787. 'rpush' => '\Predis\Commands\ListPushTail',
  788. 'pushTail' => '\Predis\Commands\ListPushTail',
  789. 'lpush' => '\Predis\Commands\ListPushHead',
  790. 'pushHead' => '\Predis\Commands\ListPushHead',
  791. 'llen' => '\Predis\Commands\ListLength',
  792. 'listLength' => '\Predis\Commands\ListLength',
  793. 'lrange' => '\Predis\Commands\ListRange',
  794. 'listRange' => '\Predis\Commands\ListRange',
  795. 'ltrim' => '\Predis\Commands\ListTrim',
  796. 'listTrim' => '\Predis\Commands\ListTrim',
  797. 'lindex' => '\Predis\Commands\ListIndex',
  798. 'listIndex' => '\Predis\Commands\ListIndex',
  799. 'lset' => '\Predis\Commands\ListSet',
  800. 'listSet' => '\Predis\Commands\ListSet',
  801. 'lrem' => '\Predis\Commands\ListRemove',
  802. 'listRemove' => '\Predis\Commands\ListRemove',
  803. 'lpop' => '\Predis\Commands\ListPopFirst',
  804. 'popFirst' => '\Predis\Commands\ListPopFirst',
  805. 'rpop' => '\Predis\Commands\ListPopLast',
  806. 'popLast' => '\Predis\Commands\ListPopLast',
  807. /* commands operating on sets */
  808. 'sadd' => '\Predis\Commands\SetAdd',
  809. 'setAdd' => '\Predis\Commands\SetAdd',
  810. 'srem' => '\Predis\Commands\SetRemove',
  811. 'setRemove' => '\Predis\Commands\SetRemove',
  812. 'spop' => '\Predis\Commands\SetPop',
  813. 'setPop' => '\Predis\Commands\SetPop',
  814. 'smove' => '\Predis\Commands\SetMove',
  815. 'setMove' => '\Predis\Commands\SetMove',
  816. 'scard' => '\Predis\Commands\SetCardinality',
  817. 'setCardinality' => '\Predis\Commands\SetCardinality',
  818. 'sismember' => '\Predis\Commands\SetIsMember',
  819. 'setIsMember' => '\Predis\Commands\SetIsMember',
  820. 'sinter' => '\Predis\Commands\SetIntersection',
  821. 'setIntersection' => '\Predis\Commands\SetIntersection',
  822. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  823. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  824. 'sunion' => '\Predis\Commands\SetUnion',
  825. 'setUnion' => '\Predis\Commands\SetUnion',
  826. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  827. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  828. 'sdiff' => '\Predis\Commands\SetDifference',
  829. 'setDifference' => '\Predis\Commands\SetDifference',
  830. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  831. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  832. 'smembers' => '\Predis\Commands\SetMembers',
  833. 'setMembers' => '\Predis\Commands\SetMembers',
  834. 'srandmember' => '\Predis\Commands\SetRandomMember',
  835. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  836. /* multiple databases handling commands */
  837. 'select' => '\Predis\Commands\SelectDatabase',
  838. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  839. 'move' => '\Predis\Commands\MoveKey',
  840. 'moveKey' => '\Predis\Commands\MoveKey',
  841. 'flushdb' => '\Predis\Commands\FlushDatabase',
  842. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  843. 'flushall' => '\Predis\Commands\FlushAll',
  844. 'flushDatabases' => '\Predis\Commands\FlushAll',
  845. /* sorting */
  846. 'sort' => '\Predis\Commands\Sort',
  847. /* remote server control commands */
  848. 'info' => '\Predis\Commands\Info',
  849. 'slaveof' => '\Predis\Commands\SlaveOf',
  850. 'slaveOf' => '\Predis\Commands\SlaveOf',
  851. /* persistence control commands */
  852. 'save' => '\Predis\Commands\Save',
  853. 'bgsave' => '\Predis\Commands\BackgroundSave',
  854. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  855. 'lastsave' => '\Predis\Commands\LastSave',
  856. 'lastSave' => '\Predis\Commands\LastSave',
  857. 'shutdown' => '\Predis\Commands\Shutdown',
  858. );
  859. }
  860. }
  861. class RedisServer_v1_2 extends RedisServer_v1_0 {
  862. public function getVersion() { return '1.2'; }
  863. public function getSupportedCommands() {
  864. return array_merge(parent::getSupportedCommands(), array(
  865. /* commands operating on string values */
  866. 'mset' => '\Predis\Commands\SetMultiple',
  867. 'setMultiple' => '\Predis\Commands\SetMultiple',
  868. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  869. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  870. /* commands operating on lists */
  871. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  872. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  873. /* commands operating on sorted sets */
  874. 'zadd' => '\Predis\Commands\ZSetAdd',
  875. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  876. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  877. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  878. 'zrem' => '\Predis\Commands\ZSetRemove',
  879. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  880. 'zrange' => '\Predis\Commands\ZSetRange',
  881. 'zsetRange' => '\Predis\Commands\ZSetRange',
  882. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  883. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  884. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  885. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  886. 'zcard' => '\Predis\Commands\ZSetCardinality',
  887. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  888. 'zscore' => '\Predis\Commands\ZSetScore',
  889. 'zsetScore' => '\Predis\Commands\ZSetScore',
  890. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  891. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  892. /* persistence control commands */
  893. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  894. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  895. ));
  896. }
  897. }
  898. class RedisServer_vNext extends RedisServer_v1_2 {
  899. public function getVersion() { return '1.3'; }
  900. public function getSupportedCommands() {
  901. return array_merge(parent::getSupportedCommands(), array(
  902. /* miscellaneous commands */
  903. 'multi' => '\Predis\Commands\Multi',
  904. 'exec' => '\Predis\Commands\Exec',
  905. 'append' => '\Predis\Commands\Append',
  906. /* commands operating on lists */
  907. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  908. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  909. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  910. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  911. /* commands operating on sorted sets */
  912. 'zcount' => '\Predis\Commands\ZCount',
  913. 'zsetCount' => '\Predis\Commands\ZCount',
  914. ));
  915. }
  916. }
  917. /* ------------------------------------------------------------------------- */
  918. namespace Predis\Utilities;
  919. class HashRing {
  920. const DEFAULT_REPLICAS = 128;
  921. private $_ring, $_ringKeys, $_replicas;
  922. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  923. $this->_replicas = $replicas;
  924. $this->_ring = array();
  925. $this->_ringKeys = array();
  926. }
  927. public function add($node) {
  928. $nodeHash = (string) $node;
  929. $replicas = $this->_replicas;
  930. for ($i = 0; $i < $replicas; $i++) {
  931. $key = crc32($nodeHash . ':' . $i);
  932. $this->_ring[$key] = $node;
  933. }
  934. ksort($this->_ring, SORT_NUMERIC);
  935. $this->_ringKeys = array_keys($this->_ring);
  936. }
  937. public function remove($node) {
  938. $nodeHash = (string) $node;
  939. $replicas = $this->_replicas;
  940. for ($i = 0; $i < $replicas; $i++) {
  941. $key = crc32($nodeHash . ':' . $i);
  942. unset($this->_ring[$key]);
  943. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  944. return $rk !== $key;
  945. });
  946. }
  947. }
  948. public function get($key) {
  949. return $this->_ring[$this->getNodeKey($key)];
  950. }
  951. private function getNodeKey($key) {
  952. $ringKeys = $this->_ringKeys;
  953. $upper = count($ringKeys) - 1;
  954. $lower = 0;
  955. $index = 0;
  956. while ($lower <= $upper) {
  957. $index = ($lower + $upper) / 2;
  958. $item = $ringKeys[$index];
  959. if ($item > $key) {
  960. $upper = $index - 1;
  961. }
  962. else if ($item < $key) {
  963. $lower = $index + 1;
  964. }
  965. else {
  966. return $index;
  967. }
  968. }
  969. return $ringKeys[$upper];
  970. }
  971. }
  972. /* ------------------------------------------------------------------------- */
  973. namespace Predis\Commands;
  974. /* miscellaneous commands */
  975. class Ping extends \Predis\InlineCommand {
  976. public function canBeHashed() { return false; }
  977. public function getCommandId() { return 'PING'; }
  978. public function parseResponse($data) {
  979. return $data === 'PONG' ? true : false;
  980. }
  981. }
  982. class DoEcho extends \Predis\BulkCommand {
  983. public function canBeHashed() { return false; }
  984. public function getCommandId() { return 'ECHO'; }
  985. }
  986. class Auth extends \Predis\InlineCommand {
  987. public function canBeHashed() { return false; }
  988. public function getCommandId() { return 'AUTH'; }
  989. }
  990. /* connection handling */
  991. class Quit extends \Predis\InlineCommand {
  992. public function canBeHashed() { return false; }
  993. public function getCommandId() { return 'QUIT'; }
  994. public function closesConnection() { return true; }
  995. }
  996. /* commands operating on string values */
  997. class Set extends \Predis\BulkCommand {
  998. public function getCommandId() { return 'SET'; }
  999. }
  1000. class SetPreserve extends \Predis\BulkCommand {
  1001. public function getCommandId() { return 'SETNX'; }
  1002. public function parseResponse($data) { return (bool) $data; }
  1003. }
  1004. class SetMultiple extends \Predis\MultiBulkCommand {
  1005. public function canBeHashed() { return false; }
  1006. public function getCommandId() { return 'MSET'; }
  1007. }
  1008. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1009. public function canBeHashed() { return false; }
  1010. public function getCommandId() { return 'MSETNX'; }
  1011. public function parseResponse($data) { return (bool) $data; }
  1012. }
  1013. class Get extends \Predis\InlineCommand {
  1014. public function getCommandId() { return 'GET'; }
  1015. }
  1016. class GetMultiple extends \Predis\InlineCommand {
  1017. public function canBeHashed() { return false; }
  1018. public function getCommandId() { return 'MGET'; }
  1019. }
  1020. class GetSet extends \Predis\BulkCommand {
  1021. public function getCommandId() { return 'GETSET'; }
  1022. }
  1023. class Increment extends \Predis\InlineCommand {
  1024. public function getCommandId() { return 'INCR'; }
  1025. }
  1026. class IncrementBy extends \Predis\InlineCommand {
  1027. public function getCommandId() { return 'INCRBY'; }
  1028. }
  1029. class Decrement extends \Predis\InlineCommand {
  1030. public function getCommandId() { return 'DECR'; }
  1031. }
  1032. class DecrementBy extends \Predis\InlineCommand {
  1033. public function getCommandId() { return 'DECRBY'; }
  1034. }
  1035. class Exists extends \Predis\InlineCommand {
  1036. public function getCommandId() { return 'EXISTS'; }
  1037. public function parseResponse($data) { return (bool) $data; }
  1038. }
  1039. class Delete extends \Predis\InlineCommand {
  1040. public function getCommandId() { return 'DEL'; }
  1041. public function parseResponse($data) { return (bool) $data; }
  1042. }
  1043. class Type extends \Predis\InlineCommand {
  1044. public function getCommandId() { return 'TYPE'; }
  1045. }
  1046. /* commands operating on the key space */
  1047. class Keys extends \Predis\InlineCommand {
  1048. public function canBeHashed() { return false; }
  1049. public function getCommandId() { return 'KEYS'; }
  1050. public function parseResponse($data) {
  1051. // TODO: is this behaviour correct?
  1052. if (is_array($data)) {
  1053. return $data;
  1054. }
  1055. return strlen($data) > 0 ? explode(' ', $data) : array();
  1056. }
  1057. }
  1058. class RandomKey extends \Predis\InlineCommand {
  1059. public function canBeHashed() { return false; }
  1060. public function getCommandId() { return 'RANDOMKEY'; }
  1061. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1062. }
  1063. class Rename extends \Predis\InlineCommand {
  1064. public function canBeHashed() { return false; }
  1065. public function getCommandId() { return 'RENAME'; }
  1066. }
  1067. class RenamePreserve extends \Predis\InlineCommand {
  1068. public function canBeHashed() { return false; }
  1069. public function getCommandId() { return 'RENAMENX'; }
  1070. public function parseResponse($data) { return (bool) $data; }
  1071. }
  1072. class Expire extends \Predis\InlineCommand {
  1073. public function getCommandId() { return 'EXPIRE'; }
  1074. public function parseResponse($data) { return (bool) $data; }
  1075. }
  1076. class ExpireAt extends \Predis\InlineCommand {
  1077. public function getCommandId() { return 'EXPIREAT'; }
  1078. public function parseResponse($data) { return (bool) $data; }
  1079. }
  1080. class DatabaseSize extends \Predis\InlineCommand {
  1081. public function canBeHashed() { return false; }
  1082. public function getCommandId() { return 'DBSIZE'; }
  1083. }
  1084. class TimeToLive extends \Predis\InlineCommand {
  1085. public function getCommandId() { return 'TTL'; }
  1086. }
  1087. /* commands operating on lists */
  1088. class ListPushTail extends \Predis\BulkCommand {
  1089. public function getCommandId() { return 'RPUSH'; }
  1090. }
  1091. class ListPushHead extends \Predis\BulkCommand {
  1092. public function getCommandId() { return 'LPUSH'; }
  1093. }
  1094. class ListLength extends \Predis\InlineCommand {
  1095. public function getCommandId() { return 'LLEN'; }
  1096. }
  1097. class ListRange extends \Predis\InlineCommand {
  1098. public function getCommandId() { return 'LRANGE'; }
  1099. }
  1100. class ListTrim extends \Predis\InlineCommand {
  1101. public function getCommandId() { return 'LTRIM'; }
  1102. }
  1103. class ListIndex extends \Predis\InlineCommand {
  1104. public function getCommandId() { return 'LINDEX'; }
  1105. }
  1106. class ListSet extends \Predis\BulkCommand {
  1107. public function getCommandId() { return 'LSET'; }
  1108. }
  1109. class ListRemove extends \Predis\BulkCommand {
  1110. public function getCommandId() { return 'LREM'; }
  1111. }
  1112. class ListPopLastPushHead extends \Predis\InlineCommand {
  1113. public function getCommandId() { return 'RPOPLPUSH'; }
  1114. }
  1115. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1116. public function getCommandId() { return 'RPOPLPUSH'; }
  1117. }
  1118. class ListPopFirst extends \Predis\InlineCommand {
  1119. public function getCommandId() { return 'LPOP'; }
  1120. }
  1121. class ListPopLast extends \Predis\InlineCommand {
  1122. public function getCommandId() { return 'RPOP'; }
  1123. }
  1124. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1125. public function getCommandId() { return 'BLPOP'; }
  1126. }
  1127. class ListPopLastBlocking extends \Predis\InlineCommand {
  1128. public function getCommandId() { return 'BRPOP'; }
  1129. }
  1130. /* commands operating on sets */
  1131. class SetAdd extends \Predis\BulkCommand {
  1132. public function getCommandId() { return 'SADD'; }
  1133. public function parseResponse($data) { return (bool) $data; }
  1134. }
  1135. class SetRemove extends \Predis\BulkCommand {
  1136. public function getCommandId() { return 'SREM'; }
  1137. public function parseResponse($data) { return (bool) $data; }
  1138. }
  1139. class SetPop extends \Predis\InlineCommand {
  1140. public function getCommandId() { return 'SPOP'; }
  1141. }
  1142. class SetMove extends \Predis\BulkCommand {
  1143. public function canBeHashed() { return false; }
  1144. public function getCommandId() { return 'SMOVE'; }
  1145. public function parseResponse($data) { return (bool) $data; }
  1146. }
  1147. class SetCardinality extends \Predis\InlineCommand {
  1148. public function getCommandId() { return 'SCARD'; }
  1149. }
  1150. class SetIsMember extends \Predis\BulkCommand {
  1151. public function getCommandId() { return 'SISMEMBER'; }
  1152. public function parseResponse($data) { return (bool) $data; }
  1153. }
  1154. class SetIntersection extends \Predis\InlineCommand {
  1155. public function getCommandId() { return 'SINTER'; }
  1156. }
  1157. class SetIntersectionStore extends \Predis\InlineCommand {
  1158. public function getCommandId() { return 'SINTERSTORE'; }
  1159. }
  1160. class SetUnion extends \Predis\InlineCommand {
  1161. public function getCommandId() { return 'SUNION'; }
  1162. }
  1163. class SetUnionStore extends \Predis\InlineCommand {
  1164. public function getCommandId() { return 'SUNIONSTORE'; }
  1165. }
  1166. class SetDifference extends \Predis\InlineCommand {
  1167. public function getCommandId() { return 'SDIFF'; }
  1168. }
  1169. class SetDifferenceStore extends \Predis\InlineCommand {
  1170. public function getCommandId() { return 'SDIFFSTORE'; }
  1171. }
  1172. class SetMembers extends \Predis\InlineCommand {
  1173. public function getCommandId() { return 'SMEMBERS'; }
  1174. }
  1175. class SetRandomMember extends \Predis\InlineCommand {
  1176. public function getCommandId() { return 'SRANDMEMBER'; }
  1177. }
  1178. /* commands operating on sorted sets */
  1179. class ZSetAdd extends \Predis\BulkCommand {
  1180. public function getCommandId() { return 'ZADD'; }
  1181. public function parseResponse($data) { return (bool) $data; }
  1182. }
  1183. class ZSetIncrementBy extends \Predis\BulkCommand {
  1184. public function getCommandId() { return 'ZINCRBY'; }
  1185. }
  1186. class ZSetRemove extends \Predis\BulkCommand {
  1187. public function getCommandId() { return 'ZREM'; }
  1188. public function parseResponse($data) { return (bool) $data; }
  1189. }
  1190. class ZSetRange extends \Predis\InlineCommand {
  1191. public function getCommandId() { return 'ZRANGE'; }
  1192. public function parseResponse($data) {
  1193. $arguments = $this->getArguments();
  1194. if (count($arguments) === 4) {
  1195. if (strtolower($arguments[3]) === 'withscores') {
  1196. $result = array();
  1197. for ($i = 0; $i < count($data); $i++) {
  1198. $result[] = array($data[$i], $data[++$i]);
  1199. }
  1200. return $result;
  1201. }
  1202. }
  1203. return $data;
  1204. }
  1205. }
  1206. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1207. public function getCommandId() { return 'ZREVRANGE'; }
  1208. }
  1209. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1210. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1211. }
  1212. class ZCount extends \Predis\InlineCommand {
  1213. public function getCommandId() { return 'ZCOUNT'; }
  1214. }
  1215. class ZSetCardinality extends \Predis\InlineCommand {
  1216. public function getCommandId() { return 'ZCARD'; }
  1217. }
  1218. class ZSetScore extends \Predis\BulkCommand {
  1219. public function getCommandId() { return 'ZSCORE'; }
  1220. }
  1221. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1222. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1223. }
  1224. /* multiple databases handling commands */
  1225. class SelectDatabase extends \Predis\InlineCommand {
  1226. public function canBeHashed() { return false; }
  1227. public function getCommandId() { return 'SELECT'; }
  1228. }
  1229. class MoveKey extends \Predis\InlineCommand {
  1230. public function canBeHashed() { return false; }
  1231. public function getCommandId() { return 'MOVE'; }
  1232. public function parseResponse($data) { return (bool) $data; }
  1233. }
  1234. class FlushDatabase extends \Predis\InlineCommand {
  1235. public function canBeHashed() { return false; }
  1236. public function getCommandId() { return 'FLUSHDB'; }
  1237. }
  1238. class FlushAll extends \Predis\InlineCommand {
  1239. public function canBeHashed() { return false; }
  1240. public function getCommandId() { return 'FLUSHALL'; }
  1241. }
  1242. /* sorting */
  1243. class Sort extends \Predis\InlineCommand {
  1244. public function getCommandId() { return 'SORT'; }
  1245. public function filterArguments(Array $arguments) {
  1246. if (count($arguments) === 1) {
  1247. return $arguments;
  1248. }
  1249. // TODO: add more parameters checks
  1250. $query = array($arguments[0]);
  1251. $sortParams = $arguments[1];
  1252. if (isset($sortParams['by'])) {
  1253. $query[] = 'BY ' . $sortParams['by'];
  1254. }
  1255. if (isset($sortParams['get'])) {
  1256. $getargs = $sortParams['get'];
  1257. if (is_array($getargs)) {
  1258. foreach ($getargs as $getarg) {
  1259. $query[] = 'GET ' . $getarg;
  1260. }
  1261. }
  1262. else {
  1263. $query[] = 'GET ' . $getargs;
  1264. }
  1265. }
  1266. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1267. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1268. }
  1269. if (isset($sortParams['sort'])) {
  1270. $query[] = strtoupper($sortParams['sort']);
  1271. }
  1272. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1273. $query[] = 'ALPHA';
  1274. }
  1275. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1276. $query[] = 'STORE ' . $sortParams['store'];
  1277. }
  1278. return $query;
  1279. }
  1280. }
  1281. /* persistence control commands */
  1282. class Save extends \Predis\InlineCommand {
  1283. public function canBeHashed() { return false; }
  1284. public function getCommandId() { return 'SAVE'; }
  1285. }
  1286. class BackgroundSave extends \Predis\InlineCommand {
  1287. public function canBeHashed() { return false; }
  1288. public function getCommandId() { return 'BGSAVE'; }
  1289. public function parseResponse($data) {
  1290. if ($data == 'Background saving started') {
  1291. return true;
  1292. }
  1293. return $data;
  1294. }
  1295. }
  1296. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1297. public function canBeHashed() { return false; }
  1298. public function getCommandId() { return 'BGREWRITEAOF'; }
  1299. public function parseResponse($data) {
  1300. return $data == 'Background append only file rewriting started';
  1301. }
  1302. }
  1303. class LastSave extends \Predis\InlineCommand {
  1304. public function canBeHashed() { return false; }
  1305. public function getCommandId() { return 'LASTSAVE'; }
  1306. }
  1307. class Shutdown extends \Predis\InlineCommand {
  1308. public function canBeHashed() { return false; }
  1309. public function getCommandId() { return 'SHUTDOWN'; }
  1310. public function closesConnection() { return true; }
  1311. }
  1312. /* remote server control commands */
  1313. class Info extends \Predis\InlineCommand {
  1314. public function canBeHashed() { return false; }
  1315. public function getCommandId() { return 'INFO'; }
  1316. public function parseResponse($data) {
  1317. $info = array();
  1318. $infoLines = explode("\r\n", $data, -1);
  1319. foreach ($infoLines as $row) {
  1320. list($k, $v) = explode(':', $row);
  1321. if (!preg_match('/^db\d+$/', $k)) {
  1322. $info[$k] = $v;
  1323. }
  1324. else {
  1325. $db = array();
  1326. foreach (explode(',', $v) as $dbvar) {
  1327. list($dbvk, $dbvv) = explode('=', $dbvar);
  1328. $db[trim($dbvk)] = $dbvv;
  1329. }
  1330. $info[$k] = $db;
  1331. }
  1332. }
  1333. return $info;
  1334. }
  1335. }
  1336. class SlaveOf extends \Predis\InlineCommand {
  1337. public function canBeHashed() { return false; }
  1338. public function getCommandId() { return 'SLAVEOF'; }
  1339. public function filterArguments(Array $arguments) {
  1340. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1341. }
  1342. }
  1343. class Multi extends \Predis\InlineCommand {
  1344. public function canBeHashed() { return false; }
  1345. public function getCommandId() { return 'MULTI'; }
  1346. }
  1347. class Exec extends \Predis\InlineCommand {
  1348. public function canBeHashed() { return false; }
  1349. public function getCommandId() { return 'EXEC'; }
  1350. }
  1351. class Append extends \Predis\BulkCommand {
  1352. public function getCommandId() { return 'APPEND'; }
  1353. }
  1354. ?>