Syntriax.Engine/Engine.Serialization/BehaviourYamlConverter.cs

63 lines
2.1 KiB
C#
Raw Normal View History

2024-02-09 17:50:39 +03:00
using System;
using Engine.Serialization.DTOs;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Engine.Serialization;
internal class BehaviourYamlConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(BehaviourDTO);
public object ReadYaml(IParser parser, Type type)
{
if (parser.Current is not MappingStart)
throw new InvalidOperationException("Expected MappingStart");
parser.MoveNext();
var behaviour = new BehaviourDTO();
while (parser.Current != null && parser.Current is not MappingEnd)
{
var propertyName = ((Scalar)parser.Current).Value;
parser.MoveNext();
switch (propertyName)
{
2024-02-10 17:10:02 +03:00
case nameof(BehaviourDTO.ClassType):
behaviour.ClassType = ((Scalar)parser.Current).Value;
2024-02-09 17:50:39 +03:00
break;
case nameof(BehaviourDTO.Priority):
behaviour.Priority = int.Parse(((Scalar)parser.Current).Value);
break;
case nameof(BehaviourDTO.StateEnable):
behaviour.StateEnable = (StateEnableDTO)(new StateEnableYamlConverter().ReadYaml(parser, typeof(StateEnableDTO)) ?? new Exception());
break;
}
parser.MoveNext();
}
return behaviour;
}
public void WriteYaml(IEmitter emitter, object? value, Type type)
{
var behaviour = (BehaviourDTO)(value ?? throw new Exception());
StateEnableYamlConverter stateEnableYamlConverter = new();
emitter.Emit(new MappingStart());
2024-02-10 17:10:02 +03:00
emitter.Emit(new Scalar(nameof(BehaviourDTO.ClassType)));
emitter.Emit(new Scalar(behaviour.ClassType.ToString()));
2024-02-09 17:50:39 +03:00
emitter.Emit(new Scalar(nameof(BehaviourDTO.Priority)));
emitter.Emit(new Scalar(behaviour.Priority.ToString()));
emitter.Emit(new Scalar(nameof(BehaviourDTO.StateEnable)));
stateEnableYamlConverter.WriteYaml(emitter, behaviour.StateEnable, typeof(StateEnableDTO));
emitter.Emit(new MappingEnd());
}
}