using System.Reflection; using SessionZero.SzfLib.Objects; using SessionZero.SzfLib.Parser; namespace SessionZero.SzfLib.Helpers; public static class SzfHelper { /// /// Gets the SzfObject type by its type identifier attribute. /// /// /// public static Type? FindSzfObjectTypeByAttributeType(string szfType) { var obj = Assembly .GetExecutingAssembly() .GetTypes() .FirstOrDefault(t => t.GetCustomAttribute(typeof(SzfObjectAttribute)) is not null && t.GetCustomAttribute()?.TypeIdentifier == szfType); if (obj is null) return null; return obj.IsAbstract || obj.IsInterface ? null : obj; } /// /// Does basic validation of a SzfObject. /// /// /// /// 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; } /// /// Gets all sections and subsections of a SzfObject. /// /// /// public static IEnumerable GetAllSectionsAndSubsections(ISzfObject obj) { List allSections = new List(); foreach (var section in obj.Sections) { allSections.Add(section); allSections.AddRange(GetAllSubsections(section)); } return allSections; } /// /// Gets all subsections of a given section recursively. /// /// /// public static IEnumerable GetAllSubsections(SzfSection section) { List subsections = new List(); foreach (var subsection in section.Subsections.Values) { subsections.Add(subsection); subsections.AddRange(GetAllSubsections(subsection)); } return subsections; } /// /// Gets all fields from all sections and subsections of an SzfObject. /// /// /// public static IEnumerable GetAllFields(ISzfObject obj) { List allFields = new List(); foreach (var section in GetAllSectionsAndSubsections(obj)) { allFields.AddRange(section.Fields.Values); } return allFields; } }