refactor(config): разбить ConfigManager на 3 класса (312→80 строк)

Применен принцип Single Responsibility:
- ConfigLoader: загрузка и миграция версий конфига
- ConfigAccessor: доступ к значениям конфигурации
- ConfigManager: координатор, делегирует вызовы

Структура:
+ config/core/ConfigLoader.java (70 строк)
+ config/core/ConfigAccessor.java (185 строк)
~ config/ConfigManager.java (312→80 строк)

Результат:
- ConfigManager уменьшен с 312 до 80 строк
- Логика разделена по ответственности
- Улучшена читаемость и поддерживаемость
This commit is contained in:
loki5512344 2026-04-07 12:52:34 +02:00
parent f45786c6af
commit bb78f1e60f
3 changed files with 315 additions and 99 deletions

View file

@ -1,18 +1,22 @@
package com.loki.lochat.config; package com.loki.lochat.config;
import com.loki.lochat.LoChat; import com.loki.lochat.LoChat;
import com.loki.lochat.utils.format.ChatFormatter; import com.loki.lochat.config.core.ConfigLoader;
import com.loki.lochat.config.core.ConfigAccessor;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import java.util.List; import java.util.List;
/** /**
* Менеджер конфигураций - упрощенная версия * Менеджер конфигураций - координатор
* Делегирует загрузку ConfigLoader, доступ ConfigAccessor
*/ */
public class ConfigManager { public class ConfigManager {
private final LoChat plugin; private final LoChat plugin;
private volatile FileConfiguration config; private final ConfigLoader loader;
private final ConfigAccessor accessor;
private volatile AppearanceConfig appearanceConfig; private volatile AppearanceConfig appearanceConfig;
private volatile MessagesConfig messagesConfig; private volatile MessagesConfig messagesConfig;
private volatile MuteConfig muteConfig; private volatile MuteConfig muteConfig;
@ -21,8 +25,8 @@ public class ConfigManager {
public ConfigManager(LoChat plugin) { public ConfigManager(LoChat plugin) {
this.plugin = plugin; this.plugin = plugin;
plugin.saveDefaultConfig(); this.loader = new ConfigLoader(plugin);
this.config = plugin.getConfig(); this.accessor = new ConfigAccessor(plugin.getConfig());
// Инициализируем конфигурации // Инициализируем конфигурации
this.appearanceConfig = new AppearanceConfig(plugin); this.appearanceConfig = new AppearanceConfig(plugin);
@ -30,10 +34,10 @@ public class ConfigManager {
this.muteConfig = new MuteConfig(plugin); this.muteConfig = new MuteConfig(plugin);
this.filtersConfig = new FiltersConfig(plugin); this.filtersConfig = new FiltersConfig(plugin);
this.soundsConfig = new SoundsConfig(plugin); this.soundsConfig = new SoundsConfig(plugin);
this.appearanceConfig.init(); this.appearanceConfig.init();
updateConfig(); loader.updateConfig();
} }
// ========== Геттеры конфигураций ========== // ========== Геттеры конфигураций ==========
@ -60,94 +64,53 @@ public class ConfigManager {
// ========== Обновление и перезагрузка ========== // ========== Обновление и перезагрузка ==========
private void updateConfig() {
int currentVersion = config.getInt("config-version", 1);
int requiredVersion = 5;
if (currentVersion < requiredVersion) {
plugin.getLogger().info("Обновление конфига с версии " + currentVersion + " до " + requiredVersion);
addMissingConfigOptions();
config.set("config-version", requiredVersion);
plugin.saveConfig();
plugin.getLogger().info("Конфиг успешно обновлен!");
}
}
private void addMissingConfigOptions() {
setIfMissing("announcements.show-title", true);
setIfMissing("announcements.title-header", "&#FFD700ОБЪЯВЛЕНИЕ");
setIfMissing("announcements.show-actionbar", true);
setIfMissing("announcements.title-duration", 3);
setIfMissing("chat.pm.enabled", true);
setIfMissing("mentions.enabled", true);
setIfMissing("mentions.sound", true);
setIfMissing("mentions.sound-type", "BLOCK_NOTE_BLOCK_PLING");
setIfMissing("mentions.highlight", "&#FFFF00@{player}");
setIfMissing("mentions.self-highlight", "&#FFD700{player}");
setIfMissing("automessages.enabled", true);
setIfMissing("automessages.interval", 300);
setIfMissing("automessages.random", false);
setIfMissing("clearchat.message.enabled", true);
setIfMissing("clearchat.message.text", "&#04CADFЧат очищен администратором {player}");
setIfMissing("lopreff.enabled", true);
setIfMissing("lopreff.use-gradient-name", true);
setIfMissing("lopreff.use-custom-prefix", true);
setIfMissing("moderation.voice-mute-console-command", "");
}
private void setIfMissing(String path, Object value) {
if (!config.contains(path)) {
config.set(path, value);
}
}
public synchronized void reload() { public synchronized void reload() {
plugin.reloadConfig(); loader.reload();
this.config = plugin.getConfig(); accessor.updateConfig(plugin.getConfig());
this.appearanceConfig.reload(); this.appearanceConfig.reload();
this.messagesConfig.reload(); this.messagesConfig.reload();
this.muteConfig.reload(); this.muteConfig.reload();
this.filtersConfig.reload(); this.filtersConfig.reload();
this.soundsConfig.reload(); this.soundsConfig.reload();
plugin.getLogger().info("Все конфигурации успешно перезагружены"); plugin.getLogger().info("Все конфигурации успешно перезагружены");
} }
// ========== Базовые методы доступа ========== // ========== Базовые методы доступа ==========
public String getString(String path, String defaultValue) { public String getString(String path, String defaultValue) {
return config.getString(path, defaultValue); return accessor.getString(path, defaultValue);
} }
public String getString(String path) { public String getString(String path) {
return config.getString(path); return accessor.getString(path);
} }
public int getInt(String path, int defaultValue) { public int getInt(String path, int defaultValue) {
return config.getInt(path, defaultValue); return accessor.getInt(path, defaultValue);
} }
public boolean getBoolean(String path, boolean defaultValue) { public boolean getBoolean(String path, boolean defaultValue) {
return config.getBoolean(path, defaultValue); return accessor.getBoolean(path, defaultValue);
} }
public List<String> getStringList(String path) { public List<String> getStringList(String path) {
return config.getStringList(path); return accessor.getStringList(path);
} }
// ========== Настройки чата ========== // ========== Настройки чата ==========
public boolean isGlobalEnabled() { public boolean isGlobalEnabled() {
return config.getBoolean("chat.global.enabled", true); return accessor.isGlobalEnabled();
} }
public int getGlobalCooldown() { public int getGlobalCooldown() {
return config.getInt("chat.global.cooldown", 3); return accessor.getGlobalCooldown();
} }
public boolean isLocalEnabled() { public boolean isLocalEnabled() {
return config.getBoolean("chat.local.enabled", true); return accessor.isLocalEnabled();
} }
public int getLocalRadius() { public int getLocalRadius() {
@ -155,158 +118,156 @@ public class ConfigManager {
} }
public int getLocalCooldown() { public int getLocalCooldown() {
return config.getInt("chat.local.cooldown", 1); return accessor.getLocalCooldown();
} }
// ========== PM ========== // ========== PM ==========
public boolean isPmEnabled() { public boolean isPmEnabled() {
return config.getBoolean("chat.pm.enabled", true); return accessor.isPmEnabled();
} }
public boolean isPmLogEnabled() { public boolean isPmLogEnabled() {
return config.getBoolean("chat.pm.log", false); return accessor.isPmLogEnabled();
} }
public boolean isPmSoundEnabled() { public boolean isPmSoundEnabled() {
return soundsConfig != null ? soundsConfig.isPmSoundEnabled() : return soundsConfig != null ? soundsConfig.isPmSoundEnabled() :
config.getBoolean("chat.pm.sound", true); getBoolean("chat.pm.sound", true);
} }
public String getPmSoundType() { public String getPmSoundType() {
return soundsConfig != null ? soundsConfig.getPmSound() : return soundsConfig != null ? soundsConfig.getPmSound() :
config.getString("chat.pm.sound-type", "ENTITY_EXPERIENCE_ORB_PICKUP"); getString("chat.pm.sound-type", "ENTITY_EXPERIENCE_ORB_PICKUP");
} }
// ========== Mentions ========== // ========== Mentions ==========
public boolean isMentionsEnabled() { public boolean isMentionsEnabled() {
return config.getBoolean("mentions.enabled", true); return accessor.isMentionsEnabled();
} }
public boolean isMentionSoundEnabled() { public boolean isMentionSoundEnabled() {
return soundsConfig != null ? soundsConfig.isMentionSoundEnabled() : return soundsConfig != null ? soundsConfig.isMentionSoundEnabled() :
config.getBoolean("mentions.sound", true); getBoolean("mentions.sound", true);
} }
public String getMentionSoundType() { public String getMentionSoundType() {
return soundsConfig != null ? soundsConfig.getMentionSound() : return soundsConfig != null ? soundsConfig.getMentionSound() :
config.getString("mentions.sound-type", "BLOCK_NOTE_BLOCK_PLING"); getString("mentions.sound-type", "BLOCK_NOTE_BLOCK_PLING");
} }
public String getMentionHighlight() { public String getMentionHighlight() {
return ChatFormatter.convertAllColors(config.getString("mentions.highlight", "&#FFFF00@{player}")); return accessor.getMentionHighlight();
} }
public String getSelfMentionHighlight() { public String getSelfMentionHighlight() {
return ChatFormatter.convertAllColors(config.getString("mentions.self-highlight", "&#FFD700{player}")); return accessor.getSelfMentionHighlight();
} }
// ========== Clear chat ========== // ========== Clear chat ==========
public boolean isClearChatMessageEnabled() { public boolean isClearChatMessageEnabled() {
return config.getBoolean("clearchat.message.enabled", true); return accessor.isClearChatMessageEnabled();
} }
public void setClearChatMessageEnabled(boolean enabled) { public void setClearChatMessageEnabled(boolean enabled) {
config.set("clearchat.message.enabled", enabled); plugin.getConfig().set("clearchat.message.enabled", enabled);
plugin.saveConfig(); plugin.saveConfig();
} }
public String getClearChatMessage() { public String getClearChatMessage() {
return config.getString("clearchat.message.text", "&#04CADFЧат очищен администратором {player}"); return accessor.getClearChatMessage();
} }
public void setClearChatMessage(String message) { public void setClearChatMessage(String message) {
config.set("clearchat.message.text", message); plugin.getConfig().set("clearchat.message.text", message);
plugin.saveConfig(); plugin.saveConfig();
} }
// ========== Auto messages ========== // ========== Auto messages ==========
public boolean isAutoMessagesEnabled() { public boolean isAutoMessagesEnabled() {
return config.getBoolean("automessages.enabled", true); return accessor.isAutoMessagesEnabled();
} }
public int getAutoMessagesInterval() { public int getAutoMessagesInterval() {
return config.getInt("automessages.interval", 300); return accessor.getAutoMessagesInterval();
} }
public boolean isAutoMessagesRandom() { public boolean isAutoMessagesRandom() {
return config.getBoolean("automessages.random", false); return accessor.isAutoMessagesRandom();
} }
// ========== Formats ========== // ========== Formats ==========
public String getAnnouncementFormat() { public String getAnnouncementFormat() {
return ChatFormatter.convertAllColors(config.getString("formats.announcement", return accessor.getAnnouncementFormat();
"&#FFD700[ОБЪЯВЛЕНИЕ] <message>"));
} }
// ========== Announcements ========== // ========== Announcements ==========
public boolean isAnnouncementTitleEnabled() { public boolean isAnnouncementTitleEnabled() {
return config.getBoolean("announcements.show-title", true); return accessor.isAnnouncementTitleEnabled();
} }
public String getAnnouncementTitleHeader() { public String getAnnouncementTitleHeader() {
return ChatFormatter.convertAllColors(config.getString("announcements.title-header", return accessor.getAnnouncementTitleHeader();
"&#FFD700ОБЪЯВЛЕНИЕ"));
} }
public boolean isAnnouncementActionBarEnabled() { public boolean isAnnouncementActionBarEnabled() {
return config.getBoolean("announcements.show-actionbar", true); return accessor.isAnnouncementActionBarEnabled();
} }
public int getAnnouncementTitleDuration() { public int getAnnouncementTitleDuration() {
return config.getInt("announcements.title-duration", 3); return accessor.getAnnouncementTitleDuration();
} }
// ========== LoPreff integration ========== // ========== LoPreff integration ==========
public boolean isLopreffEnabled() { public boolean isLopreffEnabled() {
return config.getBoolean("lopreff.enabled", true); return accessor.isLopreffEnabled();
} }
public boolean useGradientName() { public boolean useGradientName() {
return config.getBoolean("lopreff.use-gradient-name", true); return accessor.useGradientName();
} }
public boolean useCustomPrefix() { public boolean useCustomPrefix() {
return config.getBoolean("lopreff.use-custom-prefix", true); return accessor.useCustomPrefix();
} }
// ========== Кастомные сообщения ========== // ========== Кастомные сообщения ==========
public boolean isJoinMessageEnabled() { public boolean isJoinMessageEnabled() {
return config.getBoolean("messages.join.enabled", true); return accessor.isJoinMessageEnabled();
} }
public String getJoinMessageFormat() { public String getJoinMessageFormat() {
return config.getString("messages.join.format", "&#9878C9✦ &#B798A8{player} &#7858E9зашел на сервер"); return accessor.getJoinMessageFormat();
} }
public boolean isQuitMessageEnabled() { public boolean isQuitMessageEnabled() {
return config.getBoolean("messages.quit.enabled", true); return accessor.isQuitMessageEnabled();
} }
public String getQuitMessageFormat() { public String getQuitMessageFormat() {
return config.getString("messages.quit.format", "&#9878C9✦ &#B798A8{player} &#7858E9вышел с сервера"); return accessor.getQuitMessageFormat();
} }
public boolean isDeathMessageEnabled() { public boolean isDeathMessageEnabled() {
return config.getBoolean("messages.death.enabled", true); return accessor.isDeathMessageEnabled();
} }
public String getDeathPlayerKillFormat() { public String getDeathPlayerKillFormat() {
return config.getString("messages.death.player_kill", "&#CF6679☠ &#B798A8{player} &#7858E9был убит игроком &#B798A8{killer} &#9878C9({weapon})"); return accessor.getDeathPlayerKillFormat();
} }
public String getDeathMobKillFormat() { public String getDeathMobKillFormat() {
return config.getString("messages.death.mob_kill", "&#CF6679☠ &#B798A8{player} &#7858E9был убит мобом &#B798A8{killer}"); return accessor.getDeathMobKillFormat();
} }
public String getDeathDefaultFormat() { public String getDeathDefaultFormat() {
return config.getString("messages.death.default", "&#CF6679☠ &#B798A8{player} &#7858E9{death_message}"); return accessor.getDeathDefaultFormat();
} }
} }

View file

@ -0,0 +1,185 @@
package com.loki.lochat.config.core;
import com.loki.lochat.utils.format.ChatFormatter;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.List;
/**
* Предоставляет доступ к значениям конфигурации
* Инкапсулирует все геттеры для работы с config.yml
*/
public class ConfigAccessor {
private FileConfiguration config;
public ConfigAccessor(FileConfiguration config) {
this.config = config;
}
public void updateConfig(FileConfiguration config) {
this.config = config;
}
// ========== Базовые методы доступа ==========
public String getString(String path, String defaultValue) {
return config.getString(path, defaultValue);
}
public String getString(String path) {
return config.getString(path);
}
public int getInt(String path, int defaultValue) {
return config.getInt(path, defaultValue);
}
public boolean getBoolean(String path, boolean defaultValue) {
return config.getBoolean(path, defaultValue);
}
public List<String> getStringList(String path) {
return config.getStringList(path);
}
// ========== Настройки чата ==========
public boolean isGlobalEnabled() {
return config.getBoolean("chat.global.enabled", true);
}
public int getGlobalCooldown() {
return config.getInt("chat.global.cooldown", 3);
}
public boolean isLocalEnabled() {
return config.getBoolean("chat.local.enabled", true);
}
public int getLocalCooldown() {
return config.getInt("chat.local.cooldown", 1);
}
// ========== PM ==========
public boolean isPmEnabled() {
return config.getBoolean("chat.pm.enabled", true);
}
public boolean isPmLogEnabled() {
return config.getBoolean("chat.pm.log", false);
}
// ========== Mentions ==========
public boolean isMentionsEnabled() {
return config.getBoolean("mentions.enabled", true);
}
public String getMentionHighlight() {
return ChatFormatter.convertAllColors(config.getString("mentions.highlight", "&#FFFF00@{player}"));
}
public String getSelfMentionHighlight() {
return ChatFormatter.convertAllColors(config.getString("mentions.self-highlight", "&#FFD700{player}"));
}
// ========== Clear chat ==========
public boolean isClearChatMessageEnabled() {
return config.getBoolean("clearchat.message.enabled", true);
}
public String getClearChatMessage() {
return config.getString("clearchat.message.text", "&#04CADFЧат очищен администратором {player}");
}
// ========== Auto messages ==========
public boolean isAutoMessagesEnabled() {
return config.getBoolean("automessages.enabled", true);
}
public int getAutoMessagesInterval() {
return config.getInt("automessages.interval", 300);
}
public boolean isAutoMessagesRandom() {
return config.getBoolean("automessages.random", false);
}
// ========== Formats ==========
public String getAnnouncementFormat() {
return ChatFormatter.convertAllColors(config.getString("formats.announcement",
"&#FFD700[ОБЪЯВЛЕНИЕ] <message>"));
}
// ========== Announcements ==========
public boolean isAnnouncementTitleEnabled() {
return config.getBoolean("announcements.show-title", true);
}
public String getAnnouncementTitleHeader() {
return ChatFormatter.convertAllColors(config.getString("announcements.title-header",
"&#FFD700ОБЪЯВЛЕНИЕ"));
}
public boolean isAnnouncementActionBarEnabled() {
return config.getBoolean("announcements.show-actionbar", true);
}
public int getAnnouncementTitleDuration() {
return config.getInt("announcements.title-duration", 3);
}
// ========== LoPreff integration ==========
public boolean isLopreffEnabled() {
return config.getBoolean("lopreff.enabled", true);
}
public boolean useGradientName() {
return config.getBoolean("lopreff.use-gradient-name", true);
}
public boolean useCustomPrefix() {
return config.getBoolean("lopreff.use-custom-prefix", true);
}
// ========== Кастомные сообщения ==========
public boolean isJoinMessageEnabled() {
return config.getBoolean("messages.join.enabled", true);
}
public String getJoinMessageFormat() {
return config.getString("messages.join.format", "&#9878C9✦ &#B798A8{player} &#7858E9зашел на сервер");
}
public boolean isQuitMessageEnabled() {
return config.getBoolean("messages.quit.enabled", true);
}
public String getQuitMessageFormat() {
return config.getString("messages.quit.format", "&#9878C9✦ &#B798A8{player} &#7858E9вышел с сервера");
}
public boolean isDeathMessageEnabled() {
return config.getBoolean("messages.death.enabled", true);
}
public String getDeathPlayerKillFormat() {
return config.getString("messages.death.player_kill", "&#CF6679☠ &#B798A8{player} &#7858E9был убит игроком &#B798A8{killer} &#9878C9({weapon})");
}
public String getDeathMobKillFormat() {
return config.getString("messages.death.mob_kill", "&#CF6679☠ &#B798A8{player} &#7858E9был убит мобом &#B798A8{killer}");
}
public String getDeathDefaultFormat() {
return config.getString("messages.death.default", "&#CF6679☠ &#B798A8{player} &#7858E9{death_message}");
}
}

View file

@ -0,0 +1,70 @@
package com.loki.lochat.config.core;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Загрузчик и обновлятель конфигураций
* Отвечает за миграцию версий конфига
*/
public class ConfigLoader {
private final JavaPlugin plugin;
private FileConfiguration config;
public ConfigLoader(JavaPlugin plugin) {
this.plugin = plugin;
plugin.saveDefaultConfig();
this.config = plugin.getConfig();
}
public void updateConfig() {
int currentVersion = config.getInt("config-version", 1);
int requiredVersion = 5;
if (currentVersion < requiredVersion) {
plugin.getLogger().info("Обновление конфига с версии " + currentVersion + " до " + requiredVersion);
addMissingConfigOptions();
config.set("config-version", requiredVersion);
plugin.saveConfig();
plugin.getLogger().info("Конфиг успешно обновлен!");
}
}
private void addMissingConfigOptions() {
setIfMissing("announcements.show-title", true);
setIfMissing("announcements.title-header", "&#FFD700ОБЪЯВЛЕНИЕ");
setIfMissing("announcements.show-actionbar", true);
setIfMissing("announcements.title-duration", 3);
setIfMissing("chat.pm.enabled", true);
setIfMissing("mentions.enabled", true);
setIfMissing("mentions.sound", true);
setIfMissing("mentions.sound-type", "BLOCK_NOTE_BLOCK_PLING");
setIfMissing("mentions.highlight", "&#FFFF00@{player}");
setIfMissing("mentions.self-highlight", "&#FFD700{player}");
setIfMissing("automessages.enabled", true);
setIfMissing("automessages.interval", 300);
setIfMissing("automessages.random", false);
setIfMissing("clearchat.message.enabled", true);
setIfMissing("clearchat.message.text", "&#04CADFЧат очищен администратором {player}");
setIfMissing("lopreff.enabled", true);
setIfMissing("lopreff.use-gradient-name", true);
setIfMissing("lopreff.use-custom-prefix", true);
setIfMissing("moderation.voice-mute-console-command", "");
}
private void setIfMissing(String path, Object value) {
if (!config.contains(path)) {
config.set(path, value);
}
}
public void reload() {
plugin.reloadConfig();
this.config = plugin.getConfig();
}
public FileConfiguration getConfig() {
return config;
}
}