Predis.php 69 KB

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