Predis.php 55 KB

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