feat: added state enable serialization

This commit is contained in:
Syntriax 2025-04-20 01:07:13 +03:00
parent a254bb721b
commit 9c129cefe2

View File

@ -0,0 +1,46 @@
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Factory;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Syntriax.Engine.Serialization;
public class StateEnableConverter : IEngineTypeYamlConverter
{
public bool Accepts(Type type) => typeof(IStateEnable).IsAssignableFrom(type);
public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
{
parser.Consume<MappingStart>();
TypeContainer typeContainer = (TypeContainer)rootDeserializer(typeof(TypeContainer))!;
EntityReference entityReference = (EntityReference)rootDeserializer(typeof(EntityReference))!;
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IStateEnable.Enabled)) != 0)
throw new ArgumentException($"{nameof(IStateEnable)} mapping must have a {nameof(IStateEnable.Enabled)}");
bool enabled = bool.Parse(parser.Consume<Scalar>().Value);
parser.Consume<MappingEnd>();
IStateEnable stateEnable = (IStateEnable)TypeFactory.Get(typeContainer.Type);
stateEnable.Enabled = enabled;
stateEnable.Assign((IEntity)TypeFactory.Get(entityReference.TypeContainer.Type));
return stateEnable;
}
public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
{
IStateEnable stateEnable = (IStateEnable)value!;
emitter.Emit(new MappingStart());
serializer(new TypeContainer(stateEnable), typeof(TypeContainer));
emitter.Emit(new Scalar(nameof(StateEnable.Entity)));
serializer(new EntityReference(stateEnable.Entity), typeof(EntityReference));
emitter.Emit(new Scalar(nameof(IStateEnable.Enabled)));
emitter.Emit(new Scalar(stateEnable.Enabled.ToString()));
emitter.Emit(new MappingEnd());
}
}