Predis.php 68 KB

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