Files
tbd-station-14/Content.Server/GameObjects/Components/PDA/PDAExtensions.cs
DrSmugleaf 5f71ea1c48 Add extension methods to get a player's id and tests (#3630)
* Add extension methods to get a player's id and tests

* More extensive tests

* Make inventory check for ids first

* Rename to GetHeldId and TryGetHeldId
2021-03-13 13:22:51 +11:00

81 lines
2.8 KiB
C#

#nullable enable
using System.Diagnostics.CodeAnalysis;
using Content.Server.GameObjects.Components.Access;
using Content.Server.GameObjects.Components.GUI;
using Content.Server.Interfaces.GameObjects.Components.Items;
using Robust.Shared.GameObjects;
namespace Content.Server.GameObjects.Components.PDA
{
public static class PdaExtensions
{
/// <summary>
/// Gets the id that a player is holding in their hands or inventory.
/// Order: Hands > ID slot > PDA in ID slot
/// </summary>
/// <param name="player">The player to check in.</param>
/// <returns>The id card component.</returns>
public static IdCardComponent? GetHeldId(this IEntity player)
{
IdCardComponent? firstIdInPda = null;
if (player.TryGetComponent(out IHandsComponent? hands))
{
foreach (var item in hands.GetAllHeldItems())
{
if (firstIdInPda == null &&
item.Owner.TryGetComponent(out PDAComponent? pda) &&
pda.ContainedID != null)
{
firstIdInPda = pda.ContainedID;
}
if (item.Owner.TryGetComponent(out IdCardComponent? card))
{
return card;
}
}
}
if (firstIdInPda != null)
{
return firstIdInPda;
}
IdCardComponent? firstIdInInventory = null;
if (player.TryGetComponent(out InventoryComponent? inventory))
{
foreach (var item in inventory.GetAllHeldItems())
{
if (firstIdInInventory == null &&
item.TryGetComponent(out PDAComponent? pda) &&
pda.ContainedID != null)
{
firstIdInInventory = pda.ContainedID;
}
if (item.TryGetComponent(out IdCardComponent? card))
{
return card;
}
}
}
return firstIdInInventory;
}
/// <summary>
/// Gets the id that a player is holding in their hands or inventory.
/// Order: Hands > ID slot > PDA in ID slot
/// </summary>
/// <param name="player">The player to check in.</param>
/// <param name="id">The id card component.</param>
/// <returns>true if found, false otherwise.</returns>
public static bool TryGetHeldId(this IEntity player, [NotNullWhen(true)] out IdCardComponent? id)
{
return (id = player.GetHeldId()) != null;
}
}
}