Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@ public class JsonResourceManager


public JsonResourceManager(string resourcesPath, string resourceName = null)
: this(resourcesPath, resourceName, fallBackToParentUICultures: true)
{
}

public JsonResourceManager(string resourcesPath, string resourceName, bool fallBackToParentUICultures)
{
ResourcesPath = resourcesPath;
ResourceName = resourceName;
FallBackToParentUICultures = fallBackToParentUICultures;

_jsonFileWatcher = new(resourcesPath);
_jsonFileWatcher.Changed += RefreshResourcesCache;
Expand All @@ -27,6 +33,12 @@ public JsonResourceManager(string resourcesPath, string resourceName = null)

public string ResourcesFilePath { get; private set; }

/// <summary>
/// Gets a value indicating whether to fall back to parent UI cultures
/// when a localized string is not found for the current culture.
/// </summary>
public bool FallBackToParentUICultures { get; }

public virtual ConcurrentDictionary<string, string> GetResourceSet(CultureInfo culture, bool tryParents)
{
TryLoadResourceSet(culture);
Expand Down Expand Up @@ -66,7 +78,7 @@ public virtual ConcurrentDictionary<string, string> GetResourceSet(CultureInfo c
public virtual string GetString(string name)
{
var culture = CultureInfo.CurrentUICulture;
GetResourceSet(culture, tryParents: true);
GetResourceSet(culture, tryParents: FallBackToParentUICultures);

if (_resourcesCache.IsEmpty)
{
Expand All @@ -84,6 +96,11 @@ public virtual string GetString(string name)
}
}

if (!FallBackToParentUICultures)
{
break;
}

culture = culture.Parent;
} while (culture != culture.Parent);

Expand All @@ -92,22 +109,34 @@ public virtual string GetString(string name)

public virtual string GetString(string name, CultureInfo culture)
{
GetResourceSet(culture, tryParents: true);
GetResourceSet(culture, tryParents: FallBackToParentUICultures);

if (_resourcesCache.IsEmpty)
{
return null;
}

var key = $"{ResourceName}.{culture.Name}";
if (!_resourcesCache.TryGetValue(key, out var resources))
var currentCulture = culture;
do
{
return null;
}
var key = $"{ResourceName}.{currentCulture.Name}";
if (_resourcesCache.TryGetValue(key, out var resources))
{
if (resources.TryGetValue(name, out var value))
{
return value.ToString();
}
}

return resources.TryGetValue(name, out var value)
? value.ToString()
: null;
if (!FallBackToParentUICultures)
{
break;
}

currentCulture = currentCulture.Parent;
} while (currentCulture != currentCulture.Parent);

return null;
}

private void TryLoadResourceSet(CultureInfo culture)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,13 @@ namespace My.Extensions.Localization.Json;
public class JsonLocalizationOptions : LocalizationOptions
{
public ResourcesType ResourcesType { get; set; } = ResourcesType.TypeBased;

/// <summary>
/// Gets or sets a value indicating whether to fall back to parent UI cultures
/// when a localized string is not found for the current culture.
/// </summary>
/// <remarks>
/// Defaults to <c>true</c> to maintain backward compatibility.
/// </remarks>
public bool FallBackToParentUICultures { get; set; } = true;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot use RequestLocalizationOptions.FallBackToParentUICultures instead

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 5e22a6b. Now using RequestLocalizationOptions.FallBackToParentUICultures via optional constructor injection, maintaining backward compatibility with the existing constructor.

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class JsonStringLocalizerFactory : IStringLocalizerFactory
private readonly ConcurrentDictionary<string, JsonStringLocalizer> _localizerCache = new();
private readonly string _resourcesRelativePath;
private readonly ResourcesType _resourcesType = ResourcesType.TypeBased;
private readonly bool _fallBackToParentUICultures = true;
private readonly ILoggerFactory _loggerFactory;

public JsonStringLocalizerFactory(
Expand All @@ -28,6 +29,7 @@ public JsonStringLocalizerFactory(

_resourcesRelativePath = localizationOptions.Value.ResourcesPath ?? string.Empty;
_resourcesType = localizationOptions.Value.ResourcesType;
_fallBackToParentUICultures = localizationOptions.Value.FallBackToParentUICultures;
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}

Expand Down Expand Up @@ -91,8 +93,8 @@ protected virtual JsonStringLocalizer CreateJsonStringLocalizer(
string resourceName)
{
var resourceManager = _resourcesType == ResourcesType.TypeBased
? new JsonResourceManager(resourcesPath, resourceName)
: new JsonResourceManager(resourcesPath);
? new JsonResourceManager(resourcesPath, resourceName, _fallBackToParentUICultures)
: new JsonResourceManager(resourcesPath, null, _fallBackToParentUICultures);
var logger = _loggerFactory.CreateLogger<JsonStringLocalizer>();

return new JsonStringLocalizer(resourceManager, _resourceNamesCache, logger);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
}

[Fact]
public async void CultureBasedResourcesUsesIStringLocalizer()

Check warning on line 131 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. (https://xunit.net/xunit.analyzers/rules/xUnit1048)

Check warning on line 131 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. (https://xunit.net/xunit.analyzers/rules/xUnit1048)

Check warning on line 131 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. (https://xunit.net/xunit.analyzers/rules/xUnit1048)

Check warning on line 131 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. (https://xunit.net/xunit.analyzers/rules/xUnit1048)
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
Expand Down Expand Up @@ -177,6 +177,63 @@
Assert.Equal(expected, translation);
}

[Fact]
public void GetTranslation_WithFallBackToParentUICulturesDisabled_DoesNotFallbackToParentCulture()
{
// Arrange
var localizationOptions = new Mock<IOptions<JsonLocalizationOptions>>();
localizationOptions.Setup(o => o.Value)
.Returns(() => new JsonLocalizationOptions
{
ResourcesPath = "Resources",
FallBackToParentUICultures = false
});
var localizerFactory = new JsonStringLocalizerFactory(localizationOptions.Object, NullLoggerFactory.Instance);
var location = "My.Extensions.Localization.Json.Tests";
var basename = $"{location}.Common.{nameof(Test)}";
var localizer = localizerFactory.Create(basename, location);

LocalizationHelper.SetCurrentCulture("fr-FR");

// Act
// "Yes" exists only in Test.fr.json (parent culture), not in Test.fr-FR.json
var translation = localizer["Yes"];

// Assert
// When FallBackToParentUICultures is disabled, it should not find "Yes" in fr-FR
// and return the key itself as the translation was not found
Assert.Equal("Yes", translation.Value);
Assert.True(translation.ResourceNotFound);
}

[Fact]
public void GetTranslation_WithFallBackToParentUICulturesEnabled_FallsBackToParentCulture()
{
// Arrange
var localizationOptions = new Mock<IOptions<JsonLocalizationOptions>>();
localizationOptions.Setup(o => o.Value)
.Returns(() => new JsonLocalizationOptions
{
ResourcesPath = "Resources",
FallBackToParentUICultures = true
});
var localizerFactory = new JsonStringLocalizerFactory(localizationOptions.Object, NullLoggerFactory.Instance);
var location = "My.Extensions.Localization.Json.Tests";
var basename = $"{location}.Common.{nameof(Test)}";
var localizer = localizerFactory.Create(basename, location);

LocalizationHelper.SetCurrentCulture("fr-FR");

// Act
// "Yes" exists only in Test.fr.json (parent culture), not in Test.fr-FR.json
var translation = localizer["Yes"];

// Assert
// When FallBackToParentUICultures is enabled (default), it should find "Yes" in fr (parent)
Assert.Equal("Oui", translation.Value);
Assert.False(translation.ResourceNotFound);
}

private class SharedResource
{
public string Hello { get; set; }
Expand Down