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