Files
decePubClient/Services/CoalescingStringLocalizer.cs
T

65 lines
1.8 KiB
C#
Raw Normal View History

using decePubClient.Resources;
2022-12-15 20:03:40 +01:00
using Microsoft.Extensions.Localization;
using PrivaPub.ClientModels.Resources;
2022-12-15 20:03:40 +01:00
namespace collAnon.Client.Services
{
/// <summary>
/// The app's localizer: looks a key up in Resources/AllStrings, then in PrivaPub.ClientModels' FieldsNameResource and
/// ErrorsResource, and falls back to the key itself (formatted with the arguments), so a missing key shows its
/// English text instead of failing.
/// </summary>
public sealed class CoalescingStringLocalizer(IStringLocalizer<AllStrings> baseLocalizer, IStringLocalizer<FieldsNameResource> fieldsLocalizer,
IStringLocalizer<ErrorsResource> errorsLocalizer)
2022-12-15 20:03:40 +01:00
{
public IStringLocalizer Base => baseLocalizer;
public IStringLocalizer Fields => fieldsLocalizer;
public IStringLocalizer Errors => errorsLocalizer;
2022-12-15 20:03:40 +01:00
public LocalizedString this[string name]
2022-12-15 20:03:40 +01:00
{
get
{
try
{
if (!baseLocalizer[name].ResourceNotFound)
return baseLocalizer[name];
if (!fieldsLocalizer[name].ResourceNotFound)
return fieldsLocalizer[name];
if (!errorsLocalizer[name].ResourceNotFound)
return errorsLocalizer[name];
return new(name, name, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new(name, name, true);
}
2022-12-15 20:03:40 +01:00
}
}
public LocalizedString this[string name, params object[] arguments]
2022-12-15 20:03:40 +01:00
{
get
{
try
{
if (!baseLocalizer[name].ResourceNotFound)
return baseLocalizer[name, arguments];
if (!fieldsLocalizer[name].ResourceNotFound)
return fieldsLocalizer[name, arguments];
if (!errorsLocalizer[name].ResourceNotFound)
return errorsLocalizer[name, arguments];
return new(name, string.Format(name, arguments), true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new(name, name, true);
}
2022-12-15 20:03:40 +01:00
}
}
}
}