Allow regex in keys
This commit is contained in:
parent
2a468f1a95
commit
29c5a0a102
@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
using ChaosBot.Repositories;
|
using ChaosBot.Repositories;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
@ -50,16 +51,18 @@ namespace ChaosBot
|
|||||||
*/
|
*/
|
||||||
public T GetValue<T>(string key, T defaultValue, ulong? guildId = null)
|
public T GetValue<T>(string key, T defaultValue, ulong? guildId = null)
|
||||||
{
|
{
|
||||||
if (!ConfigurationFlags.ContainsKey(key))
|
bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey);
|
||||||
|
|
||||||
|
if (!keyExists)
|
||||||
throw new ArgumentException($"Configuration does not contain key '{key}'");
|
throw new ArgumentException($"Configuration does not contain key '{key}'");
|
||||||
|
|
||||||
if (!(ConfigurationFlags[key] == typeof(T)))
|
if (!(ConfigurationFlags[realKey] == typeof(T)))
|
||||||
throw new ArgumentException($"Configuration flag '{key}<{ConfigurationFlags[key]}>' does not have type '{typeof(T)}'");
|
throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'");
|
||||||
|
|
||||||
if (guildId.HasValue)
|
if (guildId.HasValue)
|
||||||
return ConfigurationRepository.GetValue(key, guildId.Value, defaultValue);
|
return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue);
|
||||||
|
|
||||||
return _appSettingsWrapper.GetValue(key, defaultValue);
|
return _appSettingsWrapper.GetValue(realKey, defaultValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
public T GetValue<T>(string key)
|
public T GetValue<T>(string key)
|
||||||
@ -80,5 +83,26 @@ namespace ChaosBot
|
|||||||
{
|
{
|
||||||
return ConfigurationFlags.ToImmutableDictionary();
|
return ConfigurationFlags.ToImmutableDictionary();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool TryGetKeyFromRegexMatch(string key, out string realKey)
|
||||||
|
{
|
||||||
|
if (ConfigurationFlags.ContainsKey(key))
|
||||||
|
{
|
||||||
|
realKey = key;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (string configurationFlagsKey in ConfigurationFlags.Keys)
|
||||||
|
{
|
||||||
|
if (new Regex(configurationFlagsKey).IsMatch(key))
|
||||||
|
{
|
||||||
|
realKey = key;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
realKey = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user