From a2d5699771de3f01f8b3d71fd026e33f10bde7f6 Mon Sep 17 00:00:00 2001 From: YouHaveTrouble Date: Thu, 21 Mar 2024 23:56:27 +0100 Subject: [PATCH] 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. --- .../youhavetrouble/yardwatch/YardWatch.java | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/main/java/me/youhavetrouble/yardwatch/YardWatch.java b/src/main/java/me/youhavetrouble/yardwatch/YardWatch.java index 533de57..95b959f 100644 --- a/src/main/java/me/youhavetrouble/yardwatch/YardWatch.java +++ b/src/main/java/me/youhavetrouble/yardwatch/YardWatch.java @@ -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> 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); + } }