Refactor out checking logic

This commit is contained in:
Daniel_I_Am 2020-10-16 18:02:38 +02:00
parent fe59799e1f
commit f0d01f1a65
No known key found for this signature in database
GPG Key ID: 80C428FCC9743E84

View File

@ -54,13 +54,7 @@ namespace ChaosBot.ConfigHelpers
*/
public T GetValue<T>(string key, T defaultValue, ulong? guildId = null)
{
bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey);
if (!keyExists)
throw new ArgumentException($"Configuration does not contain key '{key}'");
if (!(ConfigurationFlags[realKey].type == typeof(T)))
throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'");
string realKey = EnsureKeyExistsAndTypeCorrect<T>(key);
if (guildId.HasValue)
return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue);
@ -68,6 +62,11 @@ namespace ChaosBot.ConfigHelpers
return _appSettingsWrapper.GetValue(realKey, defaultValue);
}
public T GetValue<T>(string key)
{
return GetValue<T>(key, default);
}
public T GetValueGlobalDefault<T>(string key, ulong? guildId = null)
{
bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey);
@ -80,11 +79,6 @@ namespace ChaosBot.ConfigHelpers
return GetValue(key, defaultValue);
}
public T GetValue<T>(string key)
{
return GetValue<T>(key, default);
}
public IConfigurationSection GetSection(string key)
{
return _appSettingsWrapper.GetSection(key);
@ -99,6 +93,19 @@ namespace ChaosBot.ConfigHelpers
return ConfigurationFlags.ToImmutableDictionary();
}
private string EnsureKeyExistsAndTypeCorrect<T>(string key)
{
bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey);
if (!keyExists)
throw new ArgumentException($"Configuration does not contain key '{key}'");
if (!(ConfigurationFlags[realKey].type == typeof(T)))
throw new ArgumentException(
$"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'");
return realKey;
}
private bool TryGetKeyFromRegexMatch(string key, out string realKey)
{
if (ConfigurationFlags.ContainsKey(key))