Files
Pf2eDataScrapper/Pf2e/Web/Helpers/EntitySerializer.cs
T

111 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Reflection;
using Pf2e.Common;
namespace Pf2e.Web.Helpers;
/// <summary>
/// Сериализатор сущности для отображения на веб-странице.
/// </summary>
public class EntitySerializer
{
/// <summary>
/// Результат сериализации сущности.
/// </summary>
public class SerializationResult
{
public List<FieldGroup> Groups { get; set; } = [];
}
/// <summary>
/// Группа полей.
/// </summary>
public class FieldGroup
{
public string Name { get; set; } = string.Empty;
public List<FieldInfo> Fields { get; set; } = [];
}
/// <summary>
/// Информация о поле.
/// </summary>
public class FieldInfo
{
public string Name { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
public object? Value { get; set; }
public string DisplayValue { get; set; } = string.Empty;
public bool IsImplemented { get; set; } = true;
}
/// <summary>
/// Форматтер полей сущности.
/// </summary>
public EntityFieldFormatter FieldFormatter { get; } = new();
/// <summary>
/// Сериализовать FullEntity.
/// </summary>
public SerializationResult Serialize(FullEntity fullEntity)
{
SerializationResult result = new();
// Группа для основных полей Entity
FieldGroup entityGroup = new() { Name = "Основные поля" };
AddFieldsToGroup(entityGroup, fullEntity.Entity);
result.Groups.Add(entityGroup);
// Группа для полей IEntity (SubEntity)
if (fullEntity.SubEntity != null)
{
FieldGroup subEntityGroup = new()
{
Name = "Поля " + fullEntity.SubEntity.GetType().Name,
};
AddFieldsToGroup(subEntityGroup, fullEntity.SubEntity);
result.Groups.Add(subEntityGroup);
}
return result;
}
/// <summary>
/// Добавить поля объекта в группу.
/// </summary>
private void AddFieldsToGroup(FieldGroup group, object obj)
{
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
// Пропускаем навигационные свойства Entity
if (property.Name == "Entity")
continue;
object? value = property.GetValue(obj);
FieldInfo fieldInfo = CreateFieldInfo(property, value);
group.Fields.Add(fieldInfo);
}
}
/// <summary>
/// Создать FieldInfo для свойства.
/// </summary>
/// <param name="property">Поле класса.</param>
/// <param name="value">Значение поля.</param>
/// <returns>Информация о поле.</returns>
private FieldInfo CreateFieldInfo(PropertyInfo property, object? value)
{
string? displayValue = FieldFormatter.FormatValue(value);
return new()
{
Name = property.Name,
Type = property.PropertyType.Name,
Value = value,
DisplayValue = displayValue ?? "null",
IsImplemented = displayValue is not null,
};
}
}