Files
Pf2eDataScrapper/Pf2e/Database/Model/Common/I18n/LocaleExtension.cs
T

67 lines
2.6 KiB
C#

using System.ComponentModel;
using System.Reflection;
namespace Pf2e.Database.Model.Common.I18n;
/// <summary>
/// Расширения для работы с локализацией.
/// </summary>
public static class LocaleExtension
{
/// <summary>
/// Получение строкового представления типа локализации.
/// </summary>
/// <param name="localeType">Тип локализации.</param>
/// <returns>Строковое представление типа локализации.</returns>
public static string GetTypeString(this LocaleType localeType)
{
FieldInfo fi = localeType.GetType().GetField(localeType.ToString())!;
DescriptionAttribute[] attributes = (DescriptionAttribute[])
fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length != 0 ? attributes.FirstOrDefault()?.Description : null)
?? localeType.ToString();
}
/// <summary>
/// Получение типа локализации по строковому представлению типа локализации.
/// </summary>
/// <param name="localeTypeString">Строковое представление типа локализации.</param>
/// <returns>Тип локализации.</returns>
/// <exception cref="InvalidEnumArgumentException">Исключение, если строковое представление не соответсвует ни одному типу локализации.</exception>
public static LocaleType GetTypeByString(this string localeTypeString)
{
foreach (FieldInfo field in typeof(LocaleType).GetFields())
{
if (
Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
is not DescriptionAttribute descriptionAttribute
)
{
continue;
}
if (descriptionAttribute.Description == localeTypeString)
{
return (LocaleType)field.GetValue(null)!;
}
}
throw new InvalidEnumArgumentException();
}
/*
public static IQueryable<T> WhereLocale(
this IQueryable<T> query, Expression<Func<T, LocaleString>> expression, string searchTerm) where T : class
{
return query.Where(e => DbContext.LocaleSearch(e.Name.ToJson(), searchTerm));
}
public static IQueryable<Entity> WhereLocale(
this IQueryable<Entity> query, ICollection<string> searchTerms)
{
return query.Where(e => EF.Functions.LocaleSearchArray(e.Name.ToJson(), searchTerms));
}*/
}