using System.Collections.Concurrent; using System.Reflection; namespace zero.Localization; public abstract class Localizer : ILocalizer { /// public string LanguageCode { get; private set; } = "de"; protected ConcurrentDictionary Cache { get; private set; } = new(); /// public ILocalizer Language(string languageCode) { Cache = new(); LanguageCode = languageCode; return this; } /// public string Text(string key) => Text(key, null); /// public string Text(string key, Dictionary tokens) { if (key.IsNullOrEmpty()) { return null; } if (!Cache.TryGetValue(key, out string value)) { Translation translation = LoadTranslation(key); if (translation == null) { return null; } value = translation.Value; Cache.TryAdd(key, value); } if (tokens != null) { value = TokenReplacement.Apply(value, tokens); } return value; } /// public string Text(T enumValue) where T : Enum => Text(enumValue, null); /// public string Text(T enumValue, Dictionary tokens) where T : Enum { Type type = enumValue.GetType(); MemberInfo memInfo = type.GetMember(enumValue.ToString())[0]; return Text(memInfo.GetCustomAttribute()?.Key, tokens); } /// public string Maybe(string key) => Maybe(key, null); /// public string Maybe(string key, Dictionary tokens) { if (key.IsNullOrEmpty() || !key.StartsWith("@")) { string value = key; if (tokens != null) { value = TokenReplacement.Apply(value, tokens); } return value; } return Text(key.Substring(1), tokens); } /// /// Get translation from database or any other source /// protected abstract Translation LoadTranslation(string key); } public interface ILocalizer { /// /// Current language code /// string LanguageCode { get; } /// /// Set language for localizer /// ILocalizer Language(string languageCode); /// /// /// string Text(string key); /// /// /// string Text(string key, Dictionary tokens); /// /// Get a text string from a [Localize] attribute /// string Text(T enumValue) where T : Enum; /// /// Get a text string from a [Localize] attribute /// string Text(T enumValue, Dictionary tokens) where T : Enum; /// /// Only tries to resolve the key when it is prefixed with an @ /// string Maybe(string key); /// /// Only tries to resolve the key when it is prefixed with an @ /// string Maybe(string key, Dictionary tokens); }