Predis.php 57 KB

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