This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/MfGames.Nitride.Yaml/NitrideYamlEntityExtensions.cs

84 lines
2.3 KiB
C#

using System;
using MfGames.Gallium;
using MfGames.Nitride.Contents;
using YamlDotNet.Serialization;
namespace MfGames.Nitride.Yaml;
public static class NitrideYamlEntityExtensions
{
/// <summary>
/// Parses the entity text as a YAML file and returns the results. This
/// uses the default serializer, which may be configured.
/// </summary>
public static TType? GetTextContentYaml<TType>(
this Entity entity,
Action<DeserializerBuilder>? configure = null)
{
DeserializerBuilder builder = new();
configure?.Invoke(builder);
IDeserializer deserializer = builder.Build();
return entity.GetTextContentYaml<TType>(deserializer);
}
/// <summary>
/// Parses the entity text as a YAML file using the given serializer and
/// returns the results.
/// </summary>
public static TType? GetTextContentYaml<TType>(
this Entity entity,
IDeserializer deserializer)
{
string? text = entity.GetTextContentString();
return text != null
? deserializer.Deserialize<TType>(text)
: default;
}
/// <summary>
/// Sets the text content to the serialized value. If this is null, then
/// the text content is removed. This uses the default serializer which
/// may be configured.
/// </summary>
/// <returns>The same entity for chaining methods.</returns>
public static Entity SetTextContentYaml<TType>(
this Entity entity,
TType? value,
Action<SerializerBuilder>? configure = null)
{
SerializerBuilder builder = new();
configure?.Invoke(builder);
ISerializer serializer = builder.Build();
return SetTextContentYaml(entity, value, serializer);
}
/// <summary>
/// Sets the text content to the serialized value using the serializer
/// provided. If the value is null, then the text content is removed.
/// </summary>
/// <returns>The same entity for chaining methods.</returns>
public static Entity SetTextContentYaml<TType>(
this Entity entity,
TType? value,
ISerializer serializer)
{
if (value == null)
{
return entity.Remove<ITextContent>();
}
string yaml = serializer.Serialize(value);
return entity.SetTextContent(yaml);
}
}