Improve plugin registration logic in YardWatch

Refactored the plugin enablement checks in `YardWatch.java` to use a new method `shouldRegisterService`. This method determines if a plugin is enabled and if it provides an implementation for the Protection service, therefore enhancing plugin setup accuracy.
This commit is contained in:
2024-03-21 23:56:27 +01:00
parent 00a81efef8
commit a2d5699771
@@ -2,27 +2,51 @@ package me.youhavetrouble.yardwatch;
import me.youhavetrouble.yardwatch.hooks.GriefPreventionProtection;
import me.youhavetrouble.yardwatch.hooks.WorldGuardProtection;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
public final class YardWatch extends JavaPlugin {
@Override
public void onEnable() {
PluginManager pluginManager = getServer().getPluginManager();
if (pluginManager.isPluginEnabled("WorldGuard")) {
if (shouldRegisterService("WorldGuard")) {
getServer().getServicesManager().register(
Protection.class, new WorldGuardProtection(this), this, ServicePriority.Normal
);
}
if (pluginManager.isPluginEnabled("GriefPrevention")) {
if (shouldRegisterService("GriefPrevention")) {
getServer().getServicesManager().register(
Protection.class, new GriefPreventionProtection(this), this, ServicePriority.Normal
);
}
}
/**
* Determines whether a service should be registered for a given plugin.
* @param pluginName The name of the plugin
* @return True if the service should be registered, false otherwise
*/
private boolean shouldRegisterService(String pluginName) {
Plugin plugin = getServer().getPluginManager().getPlugin(pluginName);
if (plugin == null || !plugin.isEnabled()) return false;
List<RegisteredServiceProvider<?>> serviceProviders = getServer().getServicesManager().getRegistrations(plugin);
for (RegisteredServiceProvider<?> serviceProvider : serviceProviders) {
if (serviceProvider.getService() == Protection.class) {
return false;
}
}
return true;
}
@Override
public void onDisable() {
getServer().getServicesManager().unregisterAll(this);
}
}