Predis.php 56 KB

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