LangStr.cs
1,833 bytes
| 1 | namespace SplitApp.Shared.Kernel.Localization; |
|---|---|
| 2 | |
| 3 | public class LangStr : Dictionary<string, string> |
| 4 | { |
| 5 | public static string DefaultCulture { get; set; } = "en"; |
| 6 | |
| 7 | public new string this[string key] |
| 8 | { |
| 9 | get => base[key]; |
| 10 | set => base[key] = value; |
| 11 | } |
| 12 | |
| 13 | public LangStr() |
| 14 | { |
| 15 | } |
| 16 | |
| 17 | public LangStr(string value) : this(value, Thread.CurrentThread.CurrentUICulture.Name) |
| 18 | { |
| 19 | } |
| 20 | |
| 21 | public LangStr(string value, string culture) |
| 22 | { |
| 23 | if (culture.Length < 1) throw new ApplicationException("Culture is required!"); |
| 24 | |
| 25 | var neutralCulture = culture.Split('-')[0]; |
| 26 | this[neutralCulture] = value; |
| 27 | |
| 28 | if (!ContainsKey(DefaultCulture)) |
| 29 | { |
| 30 | this[DefaultCulture] = value; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | public string? Translate(string? culture = null) |
| 35 | { |
| 36 | if (Count == 0) return null; |
| 37 | culture = culture?.Trim() ?? Thread.CurrentThread.CurrentUICulture.Name; |
| 38 | |
| 39 | if (ContainsKey(culture)) |
| 40 | { |
| 41 | return this[culture]; |
| 42 | } |
| 43 | |
| 44 | var neutralCulture = culture.Split('-')[0]; |
| 45 | if (ContainsKey(neutralCulture)) |
| 46 | { |
| 47 | return this[neutralCulture]; |
| 48 | } |
| 49 | |
| 50 | if (ContainsKey(DefaultCulture)) |
| 51 | { |
| 52 | return this[DefaultCulture]; |
| 53 | } |
| 54 | |
| 55 | return null; |
| 56 | } |
| 57 | |
| 58 | public void SetTranslation(string value, string? culture = null) |
| 59 | { |
| 60 | culture = culture?.Trim() ?? Thread.CurrentThread.CurrentUICulture.Name; |
| 61 | var neutralCulture = culture.Split('-')[0]; |
| 62 | this[neutralCulture] = value; |
| 63 | } |
| 64 | |
| 65 | public override string ToString() |
| 66 | { |
| 67 | return Translate() ?? "????"; |
| 68 | } |
| 69 | |
| 70 | public static implicit operator string(LangStr? langStr) => langStr?.ToString() ?? "null"; |
| 71 | |
| 72 | public static implicit operator LangStr(string value) => new LangStr(value); |
| 73 | } |
| 74 | |