From e6cdc7d2ba852c4502a158463db55d8bf892d691 Mon Sep 17 00:00:00 2001 From: Auxilor Date: Mon, 25 Apr 2022 10:14:24 +0100 Subject: [PATCH] Added PlayerUtils#tryAsPlayer --- .../java/com/willfp/eco/util/PlayerUtils.java | 39 +++++++++++++++++++ .../kotlin/com/willfp/eco/util/PlayerUtils.kt | 13 +++++++ 2 files changed, 52 insertions(+) diff --git a/eco-api/src/main/java/com/willfp/eco/util/PlayerUtils.java b/eco-api/src/main/java/com/willfp/eco/util/PlayerUtils.java index d48d2c88..91d8107c 100644 --- a/eco-api/src/main/java/com/willfp/eco/util/PlayerUtils.java +++ b/eco-api/src/main/java/com/willfp/eco/util/PlayerUtils.java @@ -10,8 +10,14 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.platform.bukkit.BukkitAudiences; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.Tameable; +import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.function.Consumer; @@ -142,6 +148,39 @@ public final class PlayerUtils { } } + /** + * Try an entity as a player. + * + * @param entity The entity. + * @return The player, or null if no player could be found. + */ + @Nullable + public static Player tryAsPlayer(@Nullable final Entity entity) { + if (entity == null) { + return null; + } + + if (entity instanceof Player player) { + return player; + } + + if (entity instanceof Projectile projectile) { + ProjectileSource shooter = projectile.getShooter(); + if (shooter instanceof Player player) { + return player; + } + } + + if (entity instanceof Tameable tameable) { + AnimalTamer tamer = tameable.getOwner(); + if (tamer instanceof Player player) { + return player; + } + } + + return null; + } + private PlayerUtils() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); } diff --git a/eco-api/src/main/kotlin/com/willfp/eco/util/PlayerUtils.kt b/eco-api/src/main/kotlin/com/willfp/eco/util/PlayerUtils.kt index 11c9ac68..3c0e3174 100644 --- a/eco-api/src/main/kotlin/com/willfp/eco/util/PlayerUtils.kt +++ b/eco-api/src/main/kotlin/com/willfp/eco/util/PlayerUtils.kt @@ -5,6 +5,7 @@ package com.willfp.eco.util import net.kyori.adventure.audience.Audience import org.bukkit.OfflinePlayer import org.bukkit.command.CommandSender +import org.bukkit.entity.Entity import org.bukkit.entity.Player /** @@ -30,3 +31,15 @@ fun CommandSender.asAudience(): Audience = */ fun Player.runExempted(action: () -> Unit) = PlayerUtils.runExempted(this, action) + +/** + * @see PlayerUtils.runExempted + */ +fun Player.runExempted(action: (Player) -> Unit) = + PlayerUtils.runExempted(this, action) + +/** + * @see PlayerUtils.tryAsPlayer + */ +fun Entity?.tryAsPlayer(): Player? = + PlayerUtils.tryAsPlayer(this)