76 lines
2.4 KiB
C#
76 lines
2.4 KiB
C#
using System.Reflection;
|
|
using SessionZero.SzfLib.Objects;
|
|
using SessionZero.SzfLib.Parser;
|
|
|
|
namespace SessionZero.SzfLib.Helpers;
|
|
|
|
public static class SzfHelper
|
|
{
|
|
public static Type? FindSzfObjectTypeByAttributeType(string szfType)
|
|
{
|
|
var obj = Assembly
|
|
.GetExecutingAssembly()
|
|
.GetTypes()
|
|
.FirstOrDefault(t => t.GetCustomAttribute(typeof(SzfObjectAttribute)) is not null && t.GetCustomAttribute<SzfObjectAttribute>()?.TypeIdentifier == szfType);
|
|
|
|
if (obj is null) return null;
|
|
|
|
return obj.IsAbstract || obj.IsInterface ? null : obj;
|
|
}
|
|
|
|
public static SzfError BasicSzfValidation(ISzfObject obj, bool canHaveEmptyFieldValues = false)
|
|
{
|
|
SzfError result = new SzfError();
|
|
|
|
var metadataSection = obj.Sections.FirstOrDefault(s => s.Name == "Metadata");
|
|
if (metadataSection is null) result.AddError("No metadata section found");
|
|
|
|
if (obj.GetMetadataField("Name") == string.Empty) result.AddError("No metadata field name found");
|
|
|
|
foreach (var field in GetAllFields(obj))
|
|
{
|
|
var fieldValidation = field.Validate(canHaveEmptyFieldValues);
|
|
if (!fieldValidation.IsValid) result.AddError(fieldValidation.Message);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
public static IEnumerable<SzfSection> GetAllSectionsAndSubsections(ISzfObject obj)
|
|
{
|
|
List<SzfSection> allSections = new List<SzfSection>();
|
|
|
|
foreach (var section in obj.Sections)
|
|
{
|
|
allSections.Add(section);
|
|
allSections.AddRange(GetAllSubsections(section));
|
|
}
|
|
|
|
return allSections;
|
|
}
|
|
|
|
public static IEnumerable<SzfSection> GetAllSubsections(SzfSection section)
|
|
{
|
|
List<SzfSection> subsections = new List<SzfSection>();
|
|
|
|
foreach (var subsection in section.Subsections.Values)
|
|
{
|
|
subsections.Add(subsection);
|
|
subsections.AddRange(GetAllSubsections(subsection));
|
|
}
|
|
|
|
return subsections;
|
|
}
|
|
|
|
public static IEnumerable<SzfField> GetAllFields(ISzfObject obj)
|
|
{
|
|
List<SzfField> allFields = new List<SzfField>();
|
|
|
|
foreach (var section in GetAllSectionsAndSubsections(obj))
|
|
{
|
|
allFields.AddRange(section.Fields.Values);
|
|
}
|
|
|
|
return allFields;
|
|
}
|
|
} |