Predis.php 55 KB

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