PlanTempusApp/Core/Configurations/ConfigurationManager/JsonConfigurationSection.cs

80 lines
2.6 KiB
C#
Raw Normal View History

2025-01-26 22:57:27 +01:00
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
2025-01-28 14:51:09 +01:00
namespace Configuration.Core
2025-01-26 22:57:27 +01:00
{
2025-01-28 14:51:09 +01:00
public class JsonConfigurationSection : IConfigurationSection
2025-01-26 22:57:27 +01:00
{
2025-01-28 14:51:09 +01:00
private readonly JObject _data;
private readonly string _path;
private readonly string _normalizedPath;
2025-01-26 22:57:27 +01:00
2025-01-28 14:51:09 +01:00
public JsonConfigurationSection(JObject data, string path)
{
_data = data ?? throw new ArgumentNullException(nameof(data));
_path = path ?? throw new ArgumentNullException(nameof(path));
_normalizedPath = NormalizePath(_path);
}
2025-01-26 22:57:27 +01:00
2025-01-28 14:51:09 +01:00
public string this[string key]
{
get
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException(nameof(key));
2025-01-26 22:57:27 +01:00
2025-01-28 14:51:09 +01:00
var token = _data.SelectToken($"{_normalizedPath}.{NormalizePath(key)}");
return token?.ToString();
}
set => throw new NotImplementedException("Setting values is not supported.");
}
2025-01-26 22:57:27 +01:00
2025-01-28 14:51:09 +01:00
public string Key => _path.Split(':').Last();
public string Path => _path;
2025-01-26 22:57:27 +01:00
2025-01-28 14:51:09 +01:00
public string Value
{
get
{
var token = _data.SelectToken(_normalizedPath);
return token?.ToString();
}
set => throw new NotImplementedException("Setting values is not supported.");
}
2025-01-26 22:57:27 +01:00
2025-01-28 14:51:09 +01:00
public IConfigurationSection GetSection(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException(nameof(key));
return new JsonConfigurationSection(_data, string.IsNullOrEmpty(_path) ? key : $"{_path}:{key}");
}
public JToken GetToken() => _data.SelectToken(_normalizedPath);
public IEnumerable<IConfigurationSection> GetChildren()
2025-01-26 22:57:27 +01:00
{
2025-01-28 14:51:09 +01:00
var token = _data.SelectToken(_normalizedPath);
if (token is JObject obj)
{
return obj.Properties()
.Select(p => new JsonConfigurationSection(_data, string.IsNullOrEmpty(_path) ? p.Name : $"{_path}:{p.Name}"));
}
return Enumerable.Empty<IConfigurationSection>();
2025-01-26 22:57:27 +01:00
}
2025-01-28 14:51:09 +01:00
public T Get<T>() where T : class
{
var token = _data.SelectToken(_normalizedPath);
return token?.ToObject<T>();
}
public IChangeToken GetReloadToken() => new ConfigurationReloadToken();
private static string NormalizePath(string path)
{
return path?.Replace(":", ".", StringComparison.Ordinal) ?? string.Empty;
}
}
2025-01-26 22:57:27 +01:00
}