67 lines
2.7 KiB
Java
67 lines
2.7 KiB
Java
package cn.citycraft.VbariableAPI;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.Map.Entry;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
import org.bukkit.ChatColor;
|
|
import org.bukkit.entity.Player;
|
|
|
|
/**
|
|
*
|
|
* @since 2016年1月30日 上午9:29:54
|
|
* @author 喵♂呜
|
|
*/
|
|
public class VAPI {
|
|
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("[%]([a-zA-Z0-9_.-@-]+)[%]");
|
|
private static final Pattern BRACKET_PLACEHOLDER_PATTERN = Pattern.compile("[{]([a-zA-Z0-9_.-@-]+)[}]");
|
|
private static Map<String, VariableHook> placeholders = new HashMap<>();
|
|
|
|
public static boolean registerPlaceholderHook(final String plugin, final VariableHook placeholderHook) {
|
|
if (plugin == null || placeholderHook == null || VAPI.placeholders.containsKey(plugin)) {
|
|
return false;
|
|
}
|
|
VAPI.placeholders.put(plugin, placeholderHook);
|
|
return true;
|
|
}
|
|
|
|
public static String replaceVariable(final Player player, String text) {
|
|
if (text == null || VAPI.placeholders == null || VAPI.placeholders.isEmpty()) {
|
|
return text;
|
|
}
|
|
final Matcher placeholderMatcher = VAPI.PLACEHOLDER_PATTERN.matcher(text);
|
|
while (placeholderMatcher.find()) {
|
|
final String format = placeholderMatcher.group(1);
|
|
final StringBuilder pluginBuilder = new StringBuilder();
|
|
char[] formatArray;
|
|
int i;
|
|
for (formatArray = format.toCharArray(), i = 0; i < formatArray.length && formatArray[i] != '_'; ++i) {
|
|
pluginBuilder.append(formatArray[i]);
|
|
}
|
|
final String pl = pluginBuilder.toString();
|
|
final StringBuilder identifierBuilder = new StringBuilder();
|
|
for (int b = i + 1; b < formatArray.length; ++b) {
|
|
identifierBuilder.append(formatArray[b]);
|
|
}
|
|
String identifier = identifierBuilder.toString();
|
|
if (identifier.isEmpty()) {
|
|
identifier = pl;
|
|
}
|
|
for (final Entry<String, VariableHook> registered : placeholders.entrySet()) {
|
|
if (pl.equalsIgnoreCase(registered.getKey())) {
|
|
final VariableReplaceEvent vre = new VariableReplaceEvent(player, identifier);
|
|
final String value = registered.getValue().onVariableReplace(vre);
|
|
if (value == null) {
|
|
continue;
|
|
}
|
|
text = text.replaceAll("%" + format + "%", Matcher.quoteReplacement(value));
|
|
}
|
|
}
|
|
}
|
|
return ChatColor.translateAlternateColorCodes('&', text);
|
|
}
|
|
|
|
}
|