Added unregisterFlag method to FlagManager

This was requested on Discord. Enables plugs or addons to tidy up flags
if they are disabled for some reason.
This commit is contained in:
tastybento 2020-07-02 16:05:42 -07:00
parent bf36ec5dd8
commit 2b5deb4133
2 changed files with 36 additions and 2 deletions

View File

@ -122,4 +122,16 @@ public class FlagsManager {
// Remove flags
flags.values().removeIf(addon::equals);
}
/**
* Unregister a specific flag
* @param Flag - flag
* @since 1.14.0
*/
public void unregister(@NonNull Flag flag) {
// Unregister any listener
flag.getListener().ifPresent(HandlerList::unregisterAll);
// Remove flag
flags.remove(flag);
}
}

View File

@ -18,6 +18,7 @@ import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.meta.SkullMeta;
@ -39,7 +40,7 @@ import world.bentobox.bentobox.lists.Flags;
import world.bentobox.bentobox.util.Util;
@RunWith(PowerMockRunner.class)
@PrepareForTest( {BentoBox.class, Bukkit.class, Util.class} )
@PrepareForTest( {BentoBox.class, Bukkit.class, Util.class, HandlerList.class} )
public class FlagsManagerTest {
/**
@ -57,7 +58,7 @@ public class FlagsManagerTest {
public void setUp() throws Exception {
// Set up plugin
Whitebox.setInternalState(BentoBox.class, "instance", plugin);
// Util class to handle PaperLib
PowerMockito.mockStatic(Util.class);
when(Util.isPaper()).thenReturn(false);
@ -151,4 +152,25 @@ public class FlagsManagerTest {
}
/**
* Test for {@link FlagsManager#unregister(Flag)}
*/
@Test
public void testUnregisterFlag() {
PowerMockito.mockStatic(HandlerList.class);
when(plugin.isLoaded()).thenReturn(true);
FlagsManager fm = new FlagsManager(plugin);
// Listener
OriginalListener ol = new OriginalListener();
Flag originalFlag = new Flag.Builder("ORIGINAL", Material.EMERALD_BLOCK).listener(ol).build();
assertTrue(fm.registerFlag(originalFlag));
assertEquals(originalFlag, fm.getFlag("ORIGINAL").get());
// Remove
fm.unregister(originalFlag);
assertFalse(fm.getFlag("ORIGINAL").isPresent());
// Verify the listener was removed
PowerMockito.verifyStatic(HandlerList.class);
HandlerList.unregisterAll(ol);
}
}