using System.Reflection; using Pf2e.Common; namespace Pf2e.Web.Helpers; /// /// Сериализатор сущности для отображения на веб-странице. /// public class EntitySerializer { /// /// Результат сериализации сущности. /// public class SerializationResult { public List Groups { get; set; } = []; } /// /// Группа полей. /// public class FieldGroup { public string Name { get; set; } = string.Empty; public List Fields { get; set; } = []; } /// /// Информация о поле. /// 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; } /// /// Форматтер полей сущности. /// public EntityFieldFormatter FieldFormatter { get; } = new(); /// /// Сериализовать FullEntity. /// 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; } /// /// Добавить поля объекта в группу. /// 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); } } /// /// Создать FieldInfo для свойства. /// /// Поле класса. /// Значение поля. /// Информация о поле. 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, }; } }