using System; using System.Collections.Generic; namespace SabreTools.Core.Tools { public static class Converters { #region String to Enum /// /// Get bool? value from input string /// /// String to get value from /// bool? corresponding to the string public static bool? AsYesNo(this string? yesno) { return yesno?.ToLowerInvariant() switch { "yes" or "true" => true, "no" or "false" => false, _ => null, }; } /// /// Get a set of mappings from strings to enum values /// /// Enum type that is expected /// Dictionary of string to enum values public static Dictionary GenerateToEnum() { try { // Get all of the values for the enum type var values = Enum.GetValues(typeof(T)); // Build the output dictionary Dictionary mappings = []; foreach (T? value in values) { // If the value is null if (value == null) continue; // Try to get the mapping attribute MappingAttribute? attr = AttributeHelper.GetAttribute(value); if (attr?.Mappings == null || attr.Mappings.Length == 0) continue; // Loop through the mappings and add each foreach (string mapString in attr.Mappings) { if (mapString != null) mappings[mapString] = value; } } // Return the output dictionary return mappings; } catch { // This should not happen, only if the type was not an enum return []; } } #endregion #region Enum to String /// /// Get string value from input bool? /// /// bool? to get value from /// String corresponding to the bool? public static string? FromYesNo(this bool? yesno) { return yesno switch { true => "yes", false => "no", _ => null, }; } /// /// Get a set of mappings from enum values to string /// /// True to use the second mapping option, if it exists /// Enum type that is expected /// Dictionary of enum to string values public static Dictionary GenerateToString(bool useSecond) where T : notnull { try { // Get all of the values for the enum type var values = Enum.GetValues(typeof(T)); // Build the output dictionary Dictionary mappings = []; foreach (T? value in values) { // If the value is null if (value == null) continue; // Try to get the mapping attribute MappingAttribute? attr = AttributeHelper.GetAttribute(value); if (attr?.Mappings == null || attr.Mappings.Length == 0) continue; // Use either the first or second item in the list if (attr.Mappings.Length > 1 && useSecond) mappings[value] = attr.Mappings[1]; else mappings[value] = attr.Mappings[0]; } // Return the output dictionary return mappings; } catch { // This should not happen, only if the type was not an enum return []; } } #endregion } }