Predis.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  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_async':
  576. $details['connection_async'] = $v;
  577. break;
  578. case 'connection_timeout':
  579. $details['connection_timeout'] = $v;
  580. break;
  581. case 'read_write_timeout':
  582. $details['read_write_timeout'] = $v;
  583. break;
  584. case 'alias':
  585. $details['alias'] = $v;
  586. break;
  587. case 'weight':
  588. $details['weight'] = $v;
  589. break;
  590. }
  591. }
  592. $parsed = array_merge($parsed, $details);
  593. }
  594. return self::filterConnectionParams($parsed);
  595. }
  596. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  597. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  598. }
  599. private static function filterConnectionParams($parameters) {
  600. return array(
  601. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  602. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  603. 'database' => self::getParamOrDefault($parameters, 'database'),
  604. 'password' => self::getParamOrDefault($parameters, 'password'),
  605. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  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. $connectFlags = STREAM_CLIENT_CONNECT;
  646. if ($this->_params->connection_async) {
  647. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  648. }
  649. $this->_socket = @stream_socket_client(
  650. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  651. );
  652. if (!$this->_socket) {
  653. throw new ClientException(trim($errstr), $errno);
  654. }
  655. if (isset($this->_params->read_write_timeout)) {
  656. $timeoutSeconds = floor($this->_params->read_write_timeout);
  657. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  658. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  659. }
  660. if (count($this->_initCmds) > 0){
  661. $this->sendInitializationCommands();
  662. }
  663. }
  664. public function disconnect() {
  665. if ($this->isConnected()) {
  666. fclose($this->_socket);
  667. }
  668. }
  669. public function pushInitCommand(Command $command){
  670. $this->_initCmds[] = $command;
  671. }
  672. private function sendInitializationCommands() {
  673. foreach ($this->_initCmds as $command) {
  674. $this->writeCommand($command);
  675. }
  676. foreach ($this->_initCmds as $command) {
  677. $this->readResponse($command);
  678. }
  679. }
  680. public function writeCommand(Command $command) {
  681. $written = $this->writeBytes($command());
  682. if ($written === false){
  683. throw new ClientException(sprintf(
  684. 'An error has occurred while writing command %s on the network stream',
  685. $command->getCommandId()
  686. ));
  687. }
  688. }
  689. public function readResponse(Command $command) {
  690. $response = $this->_reader->read($this);
  691. $skipparse = isset($response->queued) || isset($response->error);
  692. return $skipparse ? $response : $command->parseResponse($response);
  693. }
  694. public function executeCommand(Command $command) {
  695. $this->writeCommand($command);
  696. if ($command->closesConnection()) {
  697. return $this->disconnect();
  698. }
  699. return $this->readResponse($command);
  700. }
  701. public function rawCommand($rawCommandData, $closesConnection = false) {
  702. $written = $this->writeBytes($rawCommandData);
  703. if ($written === false){
  704. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  705. }
  706. if ($closesConnection) {
  707. $this->disconnect();
  708. return;
  709. }
  710. return $this->_reader->read($this);
  711. }
  712. public function writeBytes($value) {
  713. $socket = $this->getSocket();
  714. while (($length = strlen($value)) > 0) {
  715. $written = fwrite($socket, $value);
  716. if ($length === $written) {
  717. return true;
  718. }
  719. if ($written === false || $written === 0) {
  720. return false;
  721. }
  722. $value = substr($value, $written);
  723. }
  724. return true;
  725. }
  726. public function readBytes($length) {
  727. $socket = $this->getSocket();
  728. $value = '';
  729. do {
  730. $chunk = fread($socket, $length);
  731. if ($chunk === false || $chunk === '') {
  732. return false;
  733. }
  734. $value .= $chunk;
  735. }
  736. while (($length -= strlen($chunk)) > 0);
  737. return $value;
  738. }
  739. public function readLine() {
  740. $socket = $this->getSocket();
  741. $value = '';
  742. do {
  743. $chunk = fgets($socket);
  744. if ($chunk === false || strlen($chunk) == 0) {
  745. return false;
  746. }
  747. $value .= $chunk;
  748. }
  749. while (substr($value, -2) !== ResponseReader::NEWLINE);
  750. return substr($value, 0, -2);
  751. }
  752. public function getSocket() {
  753. if (!$this->isConnected()) {
  754. $this->connect();
  755. }
  756. return $this->_socket;
  757. }
  758. public function getResponseReader() {
  759. return $this->_reader;
  760. }
  761. public function getParameters() {
  762. return $this->_params;
  763. }
  764. public function __toString() {
  765. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  766. }
  767. }
  768. class ConnectionCluster implements IConnection, \IteratorAggregate {
  769. private $_pool, $_ring;
  770. public function __construct() {
  771. $this->_pool = array();
  772. $this->_ring = new Utilities\HashRing();
  773. }
  774. public function __destruct() {
  775. $this->disconnect();
  776. }
  777. public function isConnected() {
  778. foreach ($this->_pool as $connection) {
  779. if ($connection->isConnected()) {
  780. return true;
  781. }
  782. }
  783. return false;
  784. }
  785. public function connect() {
  786. foreach ($this->_pool as $connection) {
  787. $connection->connect();
  788. }
  789. }
  790. public function disconnect() {
  791. foreach ($this->_pool as $connection) {
  792. $connection->disconnect();
  793. }
  794. }
  795. public function add(Connection $connection) {
  796. $parameters = $connection->getParameters();
  797. if (isset($parameters->alias)) {
  798. $this->_pool[$parameters->alias] = $connection;
  799. }
  800. else {
  801. $this->_pool[] = $connection;
  802. }
  803. $this->_ring->add($connection, $parameters->weight);
  804. }
  805. public function getConnection(Command $command) {
  806. if ($command->canBeHashed() === false) {
  807. throw new ClientException(
  808. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  809. );
  810. }
  811. return $this->_ring->get($command->getHash());
  812. }
  813. public function getConnectionById($id = null) {
  814. return $this->_pool[$id ?: 0];
  815. }
  816. public function getIterator() {
  817. return new \ArrayIterator($this->_pool);
  818. }
  819. public function writeCommand(Command $command) {
  820. $this->getConnection($command)->writeCommand($command);
  821. }
  822. public function readResponse(Command $command) {
  823. return $this->getConnection($command)->readResponse($command);
  824. }
  825. public function executeCommand(Command $command) {
  826. $connection = $this->getConnection($command);
  827. $connection->writeCommand($command);
  828. return $connection->readResponse($command);
  829. }
  830. }
  831. /* ------------------------------------------------------------------------- */
  832. abstract class RedisServerProfile {
  833. private static $_serverProfiles;
  834. private $_registeredCommands;
  835. public function __construct() {
  836. $this->_registeredCommands = $this->getSupportedCommands();
  837. }
  838. public abstract function getVersion();
  839. protected abstract function getSupportedCommands();
  840. public static function getDefault() {
  841. return self::get('default');
  842. }
  843. private static function predisServerProfiles() {
  844. return array(
  845. '1.0' => '\Predis\RedisServer_v1_0',
  846. '1.2' => '\Predis\RedisServer_v1_2',
  847. 'default' => '\Predis\RedisServer_v1_2',
  848. 'dev' => '\Predis\RedisServer_vNext',
  849. );
  850. }
  851. public static function get($version) {
  852. if (!isset(self::$_serverProfiles)) {
  853. self::$_serverProfiles = self::predisServerProfiles();
  854. }
  855. if (!isset(self::$_serverProfiles[$version])) {
  856. throw new ClientException("Unknown server profile: $version");
  857. }
  858. $profile = self::$_serverProfiles[$version];
  859. return new $profile();
  860. }
  861. public function compareWith($version, $operator = null) {
  862. // one could expect that PHP's version_compare would behave
  863. // the same way if invoked with 2 arguments or 3 arguments
  864. // with the third being NULL, but it is not like that.
  865. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  866. // we might need to revise the behavior of this method.
  867. return ($operator === null
  868. ? version_compare($this, $version)
  869. : version_compare($this, $version, $operator)
  870. );
  871. }
  872. public function supportsCommand($command) {
  873. return isset($this->_registeredCommands[$command]);
  874. }
  875. public function createCommand($method, $arguments = array()) {
  876. if (!isset($this->_registeredCommands[$method])) {
  877. throw new ClientException("'$method' is not a registered Redis command");
  878. }
  879. $commandClass = $this->_registeredCommands[$method];
  880. $command = new $commandClass();
  881. $command->setArgumentsArray($arguments);
  882. return $command;
  883. }
  884. public function registerCommands(Array $commands) {
  885. foreach ($commands as $command => $aliases) {
  886. $this->registerCommand($command, $aliases);
  887. }
  888. }
  889. public function registerCommand($command, $aliases) {
  890. $commandReflection = new \ReflectionClass($command);
  891. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  892. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  893. }
  894. if (is_array($aliases)) {
  895. foreach ($aliases as $alias) {
  896. $this->_registeredCommands[$alias] = $command;
  897. }
  898. }
  899. else {
  900. $this->_registeredCommands[$aliases] = $command;
  901. }
  902. }
  903. public function __toString() {
  904. return $this->getVersion();
  905. }
  906. }
  907. class RedisServer_v1_0 extends RedisServerProfile {
  908. public function getVersion() { return '1.0'; }
  909. public function getSupportedCommands() {
  910. return array(
  911. /* miscellaneous commands */
  912. 'ping' => '\Predis\Commands\Ping',
  913. 'echo' => '\Predis\Commands\DoEcho',
  914. 'auth' => '\Predis\Commands\Auth',
  915. /* connection handling */
  916. 'quit' => '\Predis\Commands\Quit',
  917. /* commands operating on string values */
  918. 'set' => '\Predis\Commands\Set',
  919. 'setnx' => '\Predis\Commands\SetPreserve',
  920. 'setPreserve' => '\Predis\Commands\SetPreserve',
  921. 'get' => '\Predis\Commands\Get',
  922. 'mget' => '\Predis\Commands\GetMultiple',
  923. 'getMultiple' => '\Predis\Commands\GetMultiple',
  924. 'getset' => '\Predis\Commands\GetSet',
  925. 'getSet' => '\Predis\Commands\GetSet',
  926. 'incr' => '\Predis\Commands\Increment',
  927. 'increment' => '\Predis\Commands\Increment',
  928. 'incrby' => '\Predis\Commands\IncrementBy',
  929. 'incrementBy' => '\Predis\Commands\IncrementBy',
  930. 'decr' => '\Predis\Commands\Decrement',
  931. 'decrement' => '\Predis\Commands\Decrement',
  932. 'decrby' => '\Predis\Commands\DecrementBy',
  933. 'decrementBy' => '\Predis\Commands\DecrementBy',
  934. 'exists' => '\Predis\Commands\Exists',
  935. 'del' => '\Predis\Commands\Delete',
  936. 'delete' => '\Predis\Commands\Delete',
  937. 'type' => '\Predis\Commands\Type',
  938. /* commands operating on the key space */
  939. 'keys' => '\Predis\Commands\Keys',
  940. 'randomkey' => '\Predis\Commands\RandomKey',
  941. 'randomKey' => '\Predis\Commands\RandomKey',
  942. 'rename' => '\Predis\Commands\Rename',
  943. 'renamenx' => '\Predis\Commands\RenamePreserve',
  944. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  945. 'expire' => '\Predis\Commands\Expire',
  946. 'expireat' => '\Predis\Commands\ExpireAt',
  947. 'expireAt' => '\Predis\Commands\ExpireAt',
  948. 'dbsize' => '\Predis\Commands\DatabaseSize',
  949. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  950. 'ttl' => '\Predis\Commands\TimeToLive',
  951. 'timeToLive' => '\Predis\Commands\TimeToLive',
  952. /* commands operating on lists */
  953. 'rpush' => '\Predis\Commands\ListPushTail',
  954. 'pushTail' => '\Predis\Commands\ListPushTail',
  955. 'lpush' => '\Predis\Commands\ListPushHead',
  956. 'pushHead' => '\Predis\Commands\ListPushHead',
  957. 'llen' => '\Predis\Commands\ListLength',
  958. 'listLength' => '\Predis\Commands\ListLength',
  959. 'lrange' => '\Predis\Commands\ListRange',
  960. 'listRange' => '\Predis\Commands\ListRange',
  961. 'ltrim' => '\Predis\Commands\ListTrim',
  962. 'listTrim' => '\Predis\Commands\ListTrim',
  963. 'lindex' => '\Predis\Commands\ListIndex',
  964. 'listIndex' => '\Predis\Commands\ListIndex',
  965. 'lset' => '\Predis\Commands\ListSet',
  966. 'listSet' => '\Predis\Commands\ListSet',
  967. 'lrem' => '\Predis\Commands\ListRemove',
  968. 'listRemove' => '\Predis\Commands\ListRemove',
  969. 'lpop' => '\Predis\Commands\ListPopFirst',
  970. 'popFirst' => '\Predis\Commands\ListPopFirst',
  971. 'rpop' => '\Predis\Commands\ListPopLast',
  972. 'popLast' => '\Predis\Commands\ListPopLast',
  973. /* commands operating on sets */
  974. 'sadd' => '\Predis\Commands\SetAdd',
  975. 'setAdd' => '\Predis\Commands\SetAdd',
  976. 'srem' => '\Predis\Commands\SetRemove',
  977. 'setRemove' => '\Predis\Commands\SetRemove',
  978. 'spop' => '\Predis\Commands\SetPop',
  979. 'setPop' => '\Predis\Commands\SetPop',
  980. 'smove' => '\Predis\Commands\SetMove',
  981. 'setMove' => '\Predis\Commands\SetMove',
  982. 'scard' => '\Predis\Commands\SetCardinality',
  983. 'setCardinality' => '\Predis\Commands\SetCardinality',
  984. 'sismember' => '\Predis\Commands\SetIsMember',
  985. 'setIsMember' => '\Predis\Commands\SetIsMember',
  986. 'sinter' => '\Predis\Commands\SetIntersection',
  987. 'setIntersection' => '\Predis\Commands\SetIntersection',
  988. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  989. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  990. 'sunion' => '\Predis\Commands\SetUnion',
  991. 'setUnion' => '\Predis\Commands\SetUnion',
  992. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  993. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  994. 'sdiff' => '\Predis\Commands\SetDifference',
  995. 'setDifference' => '\Predis\Commands\SetDifference',
  996. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  997. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  998. 'smembers' => '\Predis\Commands\SetMembers',
  999. 'setMembers' => '\Predis\Commands\SetMembers',
  1000. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1001. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  1002. /* multiple databases handling commands */
  1003. 'select' => '\Predis\Commands\SelectDatabase',
  1004. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  1005. 'move' => '\Predis\Commands\MoveKey',
  1006. 'moveKey' => '\Predis\Commands\MoveKey',
  1007. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1008. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  1009. 'flushall' => '\Predis\Commands\FlushAll',
  1010. 'flushDatabases' => '\Predis\Commands\FlushAll',
  1011. /* sorting */
  1012. 'sort' => '\Predis\Commands\Sort',
  1013. /* remote server control commands */
  1014. 'info' => '\Predis\Commands\Info',
  1015. 'slaveof' => '\Predis\Commands\SlaveOf',
  1016. 'slaveOf' => '\Predis\Commands\SlaveOf',
  1017. /* persistence control commands */
  1018. 'save' => '\Predis\Commands\Save',
  1019. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1020. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  1021. 'lastsave' => '\Predis\Commands\LastSave',
  1022. 'lastSave' => '\Predis\Commands\LastSave',
  1023. 'shutdown' => '\Predis\Commands\Shutdown',
  1024. );
  1025. }
  1026. }
  1027. class RedisServer_v1_2 extends RedisServer_v1_0 {
  1028. public function getVersion() { return '1.2'; }
  1029. public function getSupportedCommands() {
  1030. return array_merge(parent::getSupportedCommands(), array(
  1031. /* commands operating on string values */
  1032. 'mset' => '\Predis\Commands\SetMultiple',
  1033. 'setMultiple' => '\Predis\Commands\SetMultiple',
  1034. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1035. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  1036. /* commands operating on lists */
  1037. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  1038. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  1039. /* commands operating on sorted sets */
  1040. 'zadd' => '\Predis\Commands\ZSetAdd',
  1041. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  1042. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1043. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  1044. 'zrem' => '\Predis\Commands\ZSetRemove',
  1045. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  1046. 'zrange' => '\Predis\Commands\ZSetRange',
  1047. 'zsetRange' => '\Predis\Commands\ZSetRange',
  1048. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1049. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1050. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1051. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1052. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1053. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1054. 'zscore' => '\Predis\Commands\ZSetScore',
  1055. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1056. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1057. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1058. /* persistence control commands */
  1059. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1060. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1061. ));
  1062. }
  1063. }
  1064. class RedisServer_vNext extends RedisServer_v1_2 {
  1065. public function getVersion() { return '1.3'; }
  1066. public function getSupportedCommands() {
  1067. return array_merge(parent::getSupportedCommands(), array(
  1068. /* miscellaneous commands */
  1069. 'multi' => '\Predis\Commands\Multi',
  1070. 'exec' => '\Predis\Commands\Exec',
  1071. 'discard' => '\Predis\Commands\Discard',
  1072. /* commands operating on string values */
  1073. 'append' => '\Predis\Commands\Append',
  1074. 'substr' => '\Predis\Commands\Substr',
  1075. /* commands operating on lists */
  1076. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1077. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1078. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1079. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1080. /* commands operating on sorted sets */
  1081. 'zunion' => '\Predis\Commands\ZSetUnion',
  1082. 'zsetUnion' => '\Predis\Commands\ZSetUnion',
  1083. 'zinter' => '\Predis\Commands\ZSetIntersection',
  1084. 'zsetIntersection' => '\Predis\Commands\ZSetIntersection',
  1085. 'zcount' => '\Predis\Commands\ZSetCount',
  1086. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1087. 'zrank' => '\Predis\Commands\ZSetRank',
  1088. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1089. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1090. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1091. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1092. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1093. /* commands operating on hashes */
  1094. 'hset' => '\Predis\Commands\HashSet',
  1095. 'hashSet' => '\Predis\Commands\HashSet',
  1096. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1097. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1098. 'hget' => '\Predis\Commands\HashGet',
  1099. 'hashGet' => '\Predis\Commands\HashGet',
  1100. 'hdel' => '\Predis\Commands\HashDelete',
  1101. 'hashDelete' => '\Predis\Commands\HashDelete',
  1102. 'hexists' => '\Predis\Commands\HashExists',
  1103. 'hashExists' => '\Predis\Commands\HashExists',
  1104. 'hlen' => '\Predis\Commands\HashLength',
  1105. 'hashLength' => '\Predis\Commands\HashLength',
  1106. 'hkeys' => '\Predis\Commands\HashKeys',
  1107. 'hashKeys' => '\Predis\Commands\HashKeys',
  1108. 'hvals' => '\Predis\Commands\HashValues',
  1109. 'hashValues' => '\Predis\Commands\HashValues',
  1110. 'hgetall' => '\Predis\Commands\HashGetAll',
  1111. 'hashKeysValues' => '\Predis\Commands\HashGetAll',
  1112. /* remote server control commands */
  1113. 'config' => '\Predis\Commands\Config',
  1114. 'configuration' => '\Predis\Commands\Config',
  1115. ));
  1116. }
  1117. }
  1118. /* ------------------------------------------------------------------------- */
  1119. namespace Predis\Utilities;
  1120. class HashRing {
  1121. const DEFAULT_REPLICAS = 128;
  1122. const DEFAULT_WEIGHT = 100;
  1123. private $_nodes, $_ring, $_ringKeys, $_replicas;
  1124. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1125. $this->_replicas = $replicas;
  1126. $this->_nodes = array();
  1127. }
  1128. public function add($node, $weight = self::DEFAULT_WEIGHT) {
  1129. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1130. // last wins, thus the order in which nodes are added is significant.
  1131. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight);
  1132. $this->reset();
  1133. }
  1134. public function remove($node) {
  1135. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1136. // scratch, in order to reassign possible hashes with collisions to the
  1137. // right node according to the order in which they were added in the
  1138. // first place.
  1139. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1140. if ($this->_nodes[$i]['object'] === $node) {
  1141. array_splice($this->_nodes, $i, 1);
  1142. $this->reset();
  1143. break;
  1144. }
  1145. }
  1146. }
  1147. private function reset() {
  1148. unset($this->_ring);
  1149. unset($this->_ringKeys);
  1150. }
  1151. private function isInitialized() {
  1152. return isset($this->_ringKeys);
  1153. }
  1154. private function computeTotalWeight() {
  1155. // TODO: array_reduce + lambda for PHP 5.3
  1156. $totalWeight = 0;
  1157. foreach ($this->_nodes as $node) {
  1158. $totalWeight += $node['weight'];
  1159. }
  1160. return $totalWeight;
  1161. }
  1162. private function initialize() {
  1163. if ($this->isInitialized()) {
  1164. return;
  1165. }
  1166. if (count($this->_nodes) === 0) {
  1167. throw new \LogicException('Cannot initialize empty hashring');
  1168. }
  1169. $this->_ring = array();
  1170. $totalWeight = $this->computeTotalWeight();
  1171. $nodesCount = count($this->_nodes);
  1172. foreach ($this->_nodes as $node) {
  1173. $nodeObject = $node['object'];
  1174. $nodeHash = (string) $nodeObject;
  1175. $weightRatio = $node['weight'] / $totalWeight;
  1176. $replicas = (int) round($weightRatio * $nodesCount * $this->_replicas);
  1177. for ($i = 0; $i < $replicas; $i++) {
  1178. $key = crc32($nodeHash . ':' . $i);
  1179. $this->_ring[$key] = $nodeObject;
  1180. }
  1181. }
  1182. ksort($this->_ring, SORT_NUMERIC);
  1183. $this->_ringKeys = array_keys($this->_ring);
  1184. }
  1185. public function get($key) {
  1186. return $this->_ring[$this->getNodeKey($key)];
  1187. }
  1188. private function getNodeKey($key) {
  1189. // NOTE: binary search for the last item in _ringkeys with a value
  1190. // less or equal to the key. If no such item exists, return the
  1191. // last item.
  1192. $this->initialize();
  1193. $ringKeys = $this->_ringKeys;
  1194. $upper = count($ringKeys) - 1;
  1195. $lower = 0;
  1196. while ($lower <= $upper) {
  1197. $index = ($lower + $upper) >> 1;
  1198. $item = $ringKeys[$index];
  1199. if ($item > $key) {
  1200. $upper = $index - 1;
  1201. }
  1202. else if ($item < $key) {
  1203. $lower = $index + 1;
  1204. }
  1205. else {
  1206. return $item;
  1207. }
  1208. }
  1209. return $ringKeys[$upper >= 0 ? $upper : count($ringKeys) - 1];
  1210. }
  1211. }
  1212. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1213. protected $_position, $_current, $_replySize;
  1214. public function rewind() {
  1215. // NOOP
  1216. }
  1217. public function current() {
  1218. return $this->_current;
  1219. }
  1220. public function key() {
  1221. return $this->_position;
  1222. }
  1223. public function next() {
  1224. if (++$this->_position < $this->_replySize) {
  1225. $this->_current = $this->getValue();
  1226. }
  1227. return $this->_position;
  1228. }
  1229. public function valid() {
  1230. return $this->_position < $this->_replySize;
  1231. }
  1232. public function count() {
  1233. // NOTE: use count if you want to get the size of the current multi-bulk
  1234. // response without using iterator_count (which actually consumes
  1235. // our iterator to calculate the size, and we cannot perform a rewind)
  1236. return $this->_replySize;
  1237. }
  1238. protected abstract function getValue();
  1239. }
  1240. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1241. private $_connection;
  1242. public function __construct(\Predis\Connection $connection, $size) {
  1243. $this->_connection = $connection;
  1244. $this->_reader = $connection->getResponseReader();
  1245. $this->_position = 0;
  1246. $this->_current = $size > 0 ? $this->getValue() : null;
  1247. $this->_replySize = $size;
  1248. }
  1249. public function __destruct() {
  1250. // when the iterator is garbage-collected (e.g. it goes out of the
  1251. // scope of a foreach) but it has not reached its end, we must sync
  1252. // the client with the queued elements that have not been read from
  1253. // the connection with the server.
  1254. $this->sync();
  1255. }
  1256. public function sync() {
  1257. while ($this->valid()) {
  1258. $this->next();
  1259. }
  1260. }
  1261. protected function getValue() {
  1262. return $this->_reader->read($this->_connection);
  1263. }
  1264. }
  1265. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1266. private $_iterator;
  1267. public function __construct(MultiBulkResponseIterator $iterator) {
  1268. $virtualSize = count($iterator) / 2;
  1269. $this->_iterator = $iterator;
  1270. $this->_position = 0;
  1271. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1272. $this->_replySize = $virtualSize;
  1273. }
  1274. public function __destruct() {
  1275. $this->_iterator->sync();
  1276. }
  1277. protected function getValue() {
  1278. $k = $this->_iterator->current();
  1279. $this->_iterator->next();
  1280. $v = $this->_iterator->current();
  1281. $this->_iterator->next();
  1282. return array($k, $v);
  1283. }
  1284. }
  1285. /* ------------------------------------------------------------------------- */
  1286. namespace Predis\Commands;
  1287. /* miscellaneous commands */
  1288. class Ping extends \Predis\InlineCommand {
  1289. public function canBeHashed() { return false; }
  1290. public function getCommandId() { return 'PING'; }
  1291. public function parseResponse($data) {
  1292. return $data === 'PONG' ? true : false;
  1293. }
  1294. }
  1295. class DoEcho extends \Predis\BulkCommand {
  1296. public function canBeHashed() { return false; }
  1297. public function getCommandId() { return 'ECHO'; }
  1298. }
  1299. class Auth extends \Predis\InlineCommand {
  1300. public function canBeHashed() { return false; }
  1301. public function getCommandId() { return 'AUTH'; }
  1302. }
  1303. /* connection handling */
  1304. class Quit extends \Predis\InlineCommand {
  1305. public function canBeHashed() { return false; }
  1306. public function getCommandId() { return 'QUIT'; }
  1307. public function closesConnection() { return true; }
  1308. }
  1309. /* commands operating on string values */
  1310. class Set extends \Predis\BulkCommand {
  1311. public function getCommandId() { return 'SET'; }
  1312. }
  1313. class SetPreserve extends \Predis\BulkCommand {
  1314. public function getCommandId() { return 'SETNX'; }
  1315. public function parseResponse($data) { return (bool) $data; }
  1316. }
  1317. class SetMultiple extends \Predis\MultiBulkCommand {
  1318. public function canBeHashed() { return false; }
  1319. public function getCommandId() { return 'MSET'; }
  1320. }
  1321. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1322. public function canBeHashed() { return false; }
  1323. public function getCommandId() { return 'MSETNX'; }
  1324. public function parseResponse($data) { return (bool) $data; }
  1325. }
  1326. class Get extends \Predis\InlineCommand {
  1327. public function getCommandId() { return 'GET'; }
  1328. }
  1329. class GetMultiple extends \Predis\InlineCommand {
  1330. public function canBeHashed() { return false; }
  1331. public function getCommandId() { return 'MGET'; }
  1332. }
  1333. class GetSet extends \Predis\BulkCommand {
  1334. public function getCommandId() { return 'GETSET'; }
  1335. }
  1336. class Increment extends \Predis\InlineCommand {
  1337. public function getCommandId() { return 'INCR'; }
  1338. }
  1339. class IncrementBy extends \Predis\InlineCommand {
  1340. public function getCommandId() { return 'INCRBY'; }
  1341. }
  1342. class Decrement extends \Predis\InlineCommand {
  1343. public function getCommandId() { return 'DECR'; }
  1344. }
  1345. class DecrementBy extends \Predis\InlineCommand {
  1346. public function getCommandId() { return 'DECRBY'; }
  1347. }
  1348. class Exists extends \Predis\InlineCommand {
  1349. public function getCommandId() { return 'EXISTS'; }
  1350. public function parseResponse($data) { return (bool) $data; }
  1351. }
  1352. class Delete extends \Predis\InlineCommand {
  1353. public function getCommandId() { return 'DEL'; }
  1354. public function parseResponse($data) { return (bool) $data; }
  1355. }
  1356. class Type extends \Predis\InlineCommand {
  1357. public function getCommandId() { return 'TYPE'; }
  1358. }
  1359. class Append extends \Predis\BulkCommand {
  1360. public function getCommandId() { return 'APPEND'; }
  1361. }
  1362. class Substr extends \Predis\InlineCommand {
  1363. public function getCommandId() { return 'SUBSTR'; }
  1364. }
  1365. /* commands operating on the key space */
  1366. class Keys extends \Predis\InlineCommand {
  1367. public function canBeHashed() { return false; }
  1368. public function getCommandId() { return 'KEYS'; }
  1369. public function parseResponse($data) {
  1370. // TODO: is this behaviour correct?
  1371. if (is_array($data) || $data instanceof \Iterator) {
  1372. return $data;
  1373. }
  1374. return strlen($data) > 0 ? explode(' ', $data) : array();
  1375. }
  1376. }
  1377. class RandomKey extends \Predis\InlineCommand {
  1378. public function canBeHashed() { return false; }
  1379. public function getCommandId() { return 'RANDOMKEY'; }
  1380. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1381. }
  1382. class Rename extends \Predis\InlineCommand {
  1383. public function canBeHashed() { return false; }
  1384. public function getCommandId() { return 'RENAME'; }
  1385. }
  1386. class RenamePreserve extends \Predis\InlineCommand {
  1387. public function canBeHashed() { return false; }
  1388. public function getCommandId() { return 'RENAMENX'; }
  1389. public function parseResponse($data) { return (bool) $data; }
  1390. }
  1391. class Expire extends \Predis\InlineCommand {
  1392. public function getCommandId() { return 'EXPIRE'; }
  1393. public function parseResponse($data) { return (bool) $data; }
  1394. }
  1395. class ExpireAt extends \Predis\InlineCommand {
  1396. public function getCommandId() { return 'EXPIREAT'; }
  1397. public function parseResponse($data) { return (bool) $data; }
  1398. }
  1399. class DatabaseSize extends \Predis\InlineCommand {
  1400. public function canBeHashed() { return false; }
  1401. public function getCommandId() { return 'DBSIZE'; }
  1402. }
  1403. class TimeToLive extends \Predis\InlineCommand {
  1404. public function getCommandId() { return 'TTL'; }
  1405. }
  1406. /* commands operating on lists */
  1407. class ListPushTail extends \Predis\BulkCommand {
  1408. public function getCommandId() { return 'RPUSH'; }
  1409. }
  1410. class ListPushHead extends \Predis\BulkCommand {
  1411. public function getCommandId() { return 'LPUSH'; }
  1412. }
  1413. class ListLength extends \Predis\InlineCommand {
  1414. public function getCommandId() { return 'LLEN'; }
  1415. }
  1416. class ListRange extends \Predis\InlineCommand {
  1417. public function getCommandId() { return 'LRANGE'; }
  1418. }
  1419. class ListTrim extends \Predis\InlineCommand {
  1420. public function getCommandId() { return 'LTRIM'; }
  1421. }
  1422. class ListIndex extends \Predis\InlineCommand {
  1423. public function getCommandId() { return 'LINDEX'; }
  1424. }
  1425. class ListSet extends \Predis\BulkCommand {
  1426. public function getCommandId() { return 'LSET'; }
  1427. }
  1428. class ListRemove extends \Predis\BulkCommand {
  1429. public function getCommandId() { return 'LREM'; }
  1430. }
  1431. class ListPopLastPushHead extends \Predis\InlineCommand {
  1432. public function getCommandId() { return 'RPOPLPUSH'; }
  1433. }
  1434. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1435. public function getCommandId() { return 'RPOPLPUSH'; }
  1436. }
  1437. class ListPopFirst extends \Predis\InlineCommand {
  1438. public function getCommandId() { return 'LPOP'; }
  1439. }
  1440. class ListPopLast extends \Predis\InlineCommand {
  1441. public function getCommandId() { return 'RPOP'; }
  1442. }
  1443. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1444. public function getCommandId() { return 'BLPOP'; }
  1445. }
  1446. class ListPopLastBlocking extends \Predis\InlineCommand {
  1447. public function getCommandId() { return 'BRPOP'; }
  1448. }
  1449. /* commands operating on sets */
  1450. class SetAdd extends \Predis\BulkCommand {
  1451. public function getCommandId() { return 'SADD'; }
  1452. public function parseResponse($data) { return (bool) $data; }
  1453. }
  1454. class SetRemove extends \Predis\BulkCommand {
  1455. public function getCommandId() { return 'SREM'; }
  1456. public function parseResponse($data) { return (bool) $data; }
  1457. }
  1458. class SetPop extends \Predis\InlineCommand {
  1459. public function getCommandId() { return 'SPOP'; }
  1460. }
  1461. class SetMove extends \Predis\BulkCommand {
  1462. public function canBeHashed() { return false; }
  1463. public function getCommandId() { return 'SMOVE'; }
  1464. public function parseResponse($data) { return (bool) $data; }
  1465. }
  1466. class SetCardinality extends \Predis\InlineCommand {
  1467. public function getCommandId() { return 'SCARD'; }
  1468. }
  1469. class SetIsMember extends \Predis\BulkCommand {
  1470. public function getCommandId() { return 'SISMEMBER'; }
  1471. public function parseResponse($data) { return (bool) $data; }
  1472. }
  1473. class SetIntersection extends \Predis\InlineCommand {
  1474. public function getCommandId() { return 'SINTER'; }
  1475. }
  1476. class SetIntersectionStore extends \Predis\InlineCommand {
  1477. public function getCommandId() { return 'SINTERSTORE'; }
  1478. }
  1479. class SetUnion extends \Predis\InlineCommand {
  1480. public function getCommandId() { return 'SUNION'; }
  1481. }
  1482. class SetUnionStore extends \Predis\InlineCommand {
  1483. public function getCommandId() { return 'SUNIONSTORE'; }
  1484. }
  1485. class SetDifference extends \Predis\InlineCommand {
  1486. public function getCommandId() { return 'SDIFF'; }
  1487. }
  1488. class SetDifferenceStore extends \Predis\InlineCommand {
  1489. public function getCommandId() { return 'SDIFFSTORE'; }
  1490. }
  1491. class SetMembers extends \Predis\InlineCommand {
  1492. public function getCommandId() { return 'SMEMBERS'; }
  1493. }
  1494. class SetRandomMember extends \Predis\InlineCommand {
  1495. public function getCommandId() { return 'SRANDMEMBER'; }
  1496. }
  1497. /* commands operating on sorted sets */
  1498. class ZSetAdd extends \Predis\BulkCommand {
  1499. public function getCommandId() { return 'ZADD'; }
  1500. public function parseResponse($data) { return (bool) $data; }
  1501. }
  1502. class ZSetIncrementBy extends \Predis\BulkCommand {
  1503. public function getCommandId() { return 'ZINCRBY'; }
  1504. }
  1505. class ZSetRemove extends \Predis\BulkCommand {
  1506. public function getCommandId() { return 'ZREM'; }
  1507. public function parseResponse($data) { return (bool) $data; }
  1508. }
  1509. class ZSetUnion extends \Predis\InlineCommand {
  1510. public function getCommandId() { return 'ZUNION'; }
  1511. }
  1512. class ZSetIntersection extends \Predis\InlineCommand {
  1513. public function getCommandId() { return 'ZINTER'; }
  1514. }
  1515. class ZSetRange extends \Predis\InlineCommand {
  1516. public function getCommandId() { return 'ZRANGE'; }
  1517. public function parseResponse($data) {
  1518. $arguments = $this->getArguments();
  1519. if (count($arguments) === 4) {
  1520. if (strtolower($arguments[3]) === 'withscores') {
  1521. if ($data instanceof \Iterator) {
  1522. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1523. }
  1524. $result = array();
  1525. for ($i = 0; $i < count($data); $i++) {
  1526. $result[] = array($data[$i], $data[++$i]);
  1527. }
  1528. return $result;
  1529. }
  1530. }
  1531. return $data;
  1532. }
  1533. }
  1534. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1535. public function getCommandId() { return 'ZREVRANGE'; }
  1536. }
  1537. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1538. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1539. }
  1540. class ZSetCount extends \Predis\InlineCommand {
  1541. public function getCommandId() { return 'ZCOUNT'; }
  1542. }
  1543. class ZSetCardinality extends \Predis\InlineCommand {
  1544. public function getCommandId() { return 'ZCARD'; }
  1545. }
  1546. class ZSetScore extends \Predis\BulkCommand {
  1547. public function getCommandId() { return 'ZSCORE'; }
  1548. }
  1549. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1550. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1551. }
  1552. class ZSetRank extends \Predis\BulkCommand {
  1553. public function getCommandId() { return 'ZRANK'; }
  1554. }
  1555. class ZSetReverseRank extends \Predis\BulkCommand {
  1556. public function getCommandId() { return 'ZREVRANK'; }
  1557. }
  1558. class ZSetRemoveRangeByRank extends \Predis\InlineCommand {
  1559. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1560. }
  1561. /* commands operating on hashes */
  1562. class HashSet extends \Predis\MultiBulkCommand {
  1563. public function getCommandId() { return 'HSET'; }
  1564. }
  1565. class HashIncrementBy extends \Predis\InlineCommand {
  1566. public function getCommandId() { return 'HINCRBY'; }
  1567. }
  1568. class HashGet extends \Predis\BulkCommand {
  1569. public function getCommandId() { return 'HGET'; }
  1570. }
  1571. class HashDelete extends \Predis\BulkCommand {
  1572. public function getCommandId() { return 'HDEL'; }
  1573. }
  1574. class HashExists extends \Predis\BulkCommand {
  1575. public function getCommandId() { return 'HEXISTS'; }
  1576. }
  1577. class HashLength extends \Predis\InlineCommand {
  1578. public function getCommandId() { return 'HLEN'; }
  1579. }
  1580. class HashKeys extends \Predis\InlineCommand {
  1581. public function getCommandId() { return 'HKEYS'; }
  1582. }
  1583. class HashValues extends \Predis\InlineCommand {
  1584. public function getCommandId() { return 'HVALS'; }
  1585. }
  1586. class HashGetAll extends \Predis\InlineCommand {
  1587. public function getCommandId() { return 'HGETALL'; }
  1588. }
  1589. /* multiple databases handling commands */
  1590. class SelectDatabase extends \Predis\InlineCommand {
  1591. public function canBeHashed() { return false; }
  1592. public function getCommandId() { return 'SELECT'; }
  1593. }
  1594. class MoveKey extends \Predis\InlineCommand {
  1595. public function canBeHashed() { return false; }
  1596. public function getCommandId() { return 'MOVE'; }
  1597. public function parseResponse($data) { return (bool) $data; }
  1598. }
  1599. class FlushDatabase extends \Predis\InlineCommand {
  1600. public function canBeHashed() { return false; }
  1601. public function getCommandId() { return 'FLUSHDB'; }
  1602. }
  1603. class FlushAll extends \Predis\InlineCommand {
  1604. public function canBeHashed() { return false; }
  1605. public function getCommandId() { return 'FLUSHALL'; }
  1606. }
  1607. /* sorting */
  1608. class Sort extends \Predis\InlineCommand {
  1609. public function getCommandId() { return 'SORT'; }
  1610. public function filterArguments(Array $arguments) {
  1611. if (count($arguments) === 1) {
  1612. return $arguments;
  1613. }
  1614. // TODO: add more parameters checks
  1615. $query = array($arguments[0]);
  1616. $sortParams = $arguments[1];
  1617. if (isset($sortParams['by'])) {
  1618. $query[] = 'BY ' . $sortParams['by'];
  1619. }
  1620. if (isset($sortParams['get'])) {
  1621. $getargs = $sortParams['get'];
  1622. if (is_array($getargs)) {
  1623. foreach ($getargs as $getarg) {
  1624. $query[] = 'GET ' . $getarg;
  1625. }
  1626. }
  1627. else {
  1628. $query[] = 'GET ' . $getargs;
  1629. }
  1630. }
  1631. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1632. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1633. }
  1634. if (isset($sortParams['sort'])) {
  1635. $query[] = strtoupper($sortParams['sort']);
  1636. }
  1637. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1638. $query[] = 'ALPHA';
  1639. }
  1640. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1641. $query[] = 'STORE ' . $sortParams['store'];
  1642. }
  1643. return $query;
  1644. }
  1645. }
  1646. /* persistence control commands */
  1647. class Save extends \Predis\InlineCommand {
  1648. public function canBeHashed() { return false; }
  1649. public function getCommandId() { return 'SAVE'; }
  1650. }
  1651. class BackgroundSave extends \Predis\InlineCommand {
  1652. public function canBeHashed() { return false; }
  1653. public function getCommandId() { return 'BGSAVE'; }
  1654. public function parseResponse($data) {
  1655. if ($data == 'Background saving started') {
  1656. return true;
  1657. }
  1658. return $data;
  1659. }
  1660. }
  1661. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1662. public function canBeHashed() { return false; }
  1663. public function getCommandId() { return 'BGREWRITEAOF'; }
  1664. public function parseResponse($data) {
  1665. return $data == 'Background append only file rewriting started';
  1666. }
  1667. }
  1668. class LastSave extends \Predis\InlineCommand {
  1669. public function canBeHashed() { return false; }
  1670. public function getCommandId() { return 'LASTSAVE'; }
  1671. }
  1672. class Shutdown extends \Predis\InlineCommand {
  1673. public function canBeHashed() { return false; }
  1674. public function getCommandId() { return 'SHUTDOWN'; }
  1675. public function closesConnection() { return true; }
  1676. }
  1677. /* remote server control commands */
  1678. class Info extends \Predis\InlineCommand {
  1679. public function canBeHashed() { return false; }
  1680. public function getCommandId() { return 'INFO'; }
  1681. public function parseResponse($data) {
  1682. $info = array();
  1683. $infoLines = explode("\r\n", $data, -1);
  1684. foreach ($infoLines as $row) {
  1685. list($k, $v) = explode(':', $row);
  1686. if (!preg_match('/^db\d+$/', $k)) {
  1687. $info[$k] = $v;
  1688. }
  1689. else {
  1690. $db = array();
  1691. foreach (explode(',', $v) as $dbvar) {
  1692. list($dbvk, $dbvv) = explode('=', $dbvar);
  1693. $db[trim($dbvk)] = $dbvv;
  1694. }
  1695. $info[$k] = $db;
  1696. }
  1697. }
  1698. return $info;
  1699. }
  1700. }
  1701. class SlaveOf extends \Predis\InlineCommand {
  1702. public function canBeHashed() { return false; }
  1703. public function getCommandId() { return 'SLAVEOF'; }
  1704. public function filterArguments(Array $arguments) {
  1705. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1706. }
  1707. }
  1708. class Config extends \Predis\BulkCommand {
  1709. public function canBeHashed() { return false; }
  1710. public function getCommandId() { return 'CONFIG'; }
  1711. }
  1712. class Multi extends \Predis\InlineCommand {
  1713. public function canBeHashed() { return false; }
  1714. public function getCommandId() { return 'MULTI'; }
  1715. }
  1716. class Exec extends \Predis\InlineCommand {
  1717. public function canBeHashed() { return false; }
  1718. public function getCommandId() { return 'EXEC'; }
  1719. }
  1720. class Discard extends \Predis\InlineCommand {
  1721. public function canBeHashed() { return false; }
  1722. public function getCommandId() { return 'DISCARD'; }
  1723. }
  1724. ?>