Predis.php 73 KB

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