From 08f13108d8ddff52e65003b54d49540fd0bd630d Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Tue, 28 May 2024 07:10:32 +0300 Subject: [PATCH] feat: add validator for settings --- .../Validators/SettingsRequiredValidator.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Endpoint/Configuration/General/Validators/SettingsRequiredValidator.cs diff --git a/Endpoint/Configuration/General/Validators/SettingsRequiredValidator.cs b/Endpoint/Configuration/General/Validators/SettingsRequiredValidator.cs new file mode 100644 index 0000000..a1e8fbc --- /dev/null +++ b/Endpoint/Configuration/General/Validators/SettingsRequiredValidator.cs @@ -0,0 +1,38 @@ +using Microsoft.Extensions.Options; +using Mirea.Api.Endpoint.Configuration.General.Attributes; +using Mirea.Api.Endpoint.Configuration.General.Interfaces; +using System; +using System.Reflection; + +namespace Mirea.Api.Endpoint.Configuration.General.Validators; + +public class SettingsRequiredValidator +{ + private readonly GeneralConfig _generalConfig; + + public SettingsRequiredValidator(IOptionsSnapshot configuration) => + _generalConfig = configuration.Value; + + public SettingsRequiredValidator(GeneralConfig configuration) => + _generalConfig = configuration; + + public bool AreSettingsValid() + { + foreach (var property in _generalConfig + .GetType() + .GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (!Attribute.IsDefined(property.PropertyType, typeof(RequiredSettingsAttribute))) continue; + + var value = property.GetValue(_generalConfig); + if (value == null) + return false; + + var isConfigured = value as IIsConfigured; + if (!isConfigured!.IsConfigured()) + return false; + } + + return true; + } +} \ No newline at end of file