Skip to content

Commit

Permalink
Improved: AdventureCompatUtil#sendComponent
Browse files Browse the repository at this point in the history
Added: JavaDocs to AdventureCompatUtil
  • Loading branch information
Bram1903 committed Apr 28, 2024
1 parent 7f54e53 commit 2cf5b32
Showing 1 changed file with 30 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,35 @@
import java.util.UUID;
import java.util.regex.Pattern;

/**
* Utility class for managing player sending and broadcasting messages via the Adventure API,
* with compatibility for Bukkit's CommandSender.
*/
public final class AdventureCompatUtil {

private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + '&' + "[0-9A-FK-ORX]|\\\u25cf");

/**
* Sends a text component to a CommandSender.
*
* @param sender the CommandSender to send the component to.
* @param component the Component to send.
*/
public void sendComponent(CommandSender sender, Component component) {
if (sender instanceof Player) {
Optional<User> optionalUser = getUser(((Player) sender).getUniqueId());

optionalUser.ifPresent(user -> user.sendMessage(component));
getUser(((Player) sender).getUniqueId()).ifPresent(user -> user.sendMessage(component));
} else {
sendPlainMessage(sender, component);
}
}

/**
* Broadcasts a text component to all Players with a specific permission.
* If the permission is null, the component is broadcast to all Players.
*
* @param component the Component to broadcast.
* @param permission the permission required to receive the broadcast, or null to broadcast to all Players.
*/
public void broadcastComponent(Component component, @Nullable String permission) {
if (permission != null) {
Bukkit.getOnlinePlayers().stream()
Expand All @@ -38,13 +53,25 @@ public void broadcastComponent(Component component, @Nullable String permission)
}
}

/**
* Sends a plain text message to a CommandSender.
*
* @param sender the CommandSender to send the message to.
* @param component the Component to convert to plain text and send.
*/
public void sendPlainMessage(CommandSender sender, Component component) {
sender.sendMessage(STRIP_COLOR_PATTERN
.matcher(LegacyComponentSerializer.legacyAmpersand().serialize(component))
.replaceAll("")
.trim());
}

/**
* Retrieves a PacketEvents User by UUID.
*
* @param playerUUID the UUID of the Player.
* @return an Optional containing the User if one was found, or an empty Optional if no User was found.
*/
private Optional<User> getUser(UUID playerUUID) {
return PacketEvents.getAPI()
.getProtocolManager()
Expand Down

0 comments on commit 2cf5b32

Please sign in to comment.