| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ResourceDatasetLoader.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Concurrent; |
| | | 9 | | using System.Collections.Immutable; |
| | | 10 | | using System.Globalization; |
| | | 11 | | using System.Resources; |
| | | 12 | | |
| | | 13 | | namespace MyNet.Fakers.Localization; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Helper class for loading and caching resource datasets from semicolon-separated strings. |
| | | 17 | | /// </summary> |
| | | 18 | | internal static class ResourceDatasetLoader |
| | | 19 | | { |
| | 3 | 20 | | private static readonly ConcurrentDictionary<ResourceKey, ImmutableArray<string>> Cache = []; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Loads a localized string list from a RESX resource. |
| | | 24 | | /// </summary> |
| | | 25 | | /// <param name="resourceManager">The resource manager to load from.</param> |
| | | 26 | | /// <param name="key">The resource key.</param> |
| | | 27 | | /// <param name="culture">The target culture.</param> |
| | | 28 | | /// <returns>A cached read-only string list.</returns> |
| | | 29 | | public static ImmutableArray<string> LoadList(ResourceManager resourceManager, string key, CultureInfo culture) |
| | | 30 | | { |
| | 78 | 31 | | ArgumentNullException.ThrowIfNull(resourceManager); |
| | 78 | 32 | | ArgumentNullException.ThrowIfNull(key); |
| | 78 | 33 | | ArgumentNullException.ThrowIfNull(culture); |
| | | 34 | | |
| | 78 | 35 | | var cacheKey = new ResourceKey(resourceManager, key, culture.Name); |
| | | 36 | | |
| | 78 | 37 | | return Cache.GetOrAdd(cacheKey, static x => |
| | 78 | 38 | | { |
| | 78 | 39 | | var value = x.ResourceManager.GetString(x.Key, CultureInfo.GetCultureInfo(x.Culture)); |
| | 78 | 40 | | |
| | 78 | 41 | | return string.IsNullOrWhiteSpace(value) |
| | 78 | 42 | | ? [] |
| | 78 | 43 | | : [..value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)]; |
| | 78 | 44 | | }); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Represents a unique key for caching resource datasets, based on the resource type, key, and culture. |
| | | 49 | | /// </summary> |
| | | 50 | | /// <param name="ResourceManager">The resource manager.</param> |
| | | 51 | | /// <param name="Key">The resource key.</param> |
| | | 52 | | /// <param name="Culture">The target culture.</param> |
| | | 53 | | private sealed record ResourceKey(ResourceManager ResourceManager, string Key, string Culture); |
| | | 54 | | } |
| | | 55 | | |