diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-02-02 21:28:39 -0600 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-02-02 21:28:39 -0600 |
| commit | f5071fce7461949be7ffac129f283815a3ecd389 (patch) | |
| tree | a7907d86d88a3fe71ad360ad2810814694dcf3cc /src/slskd/Common/Validation/ValidationExtensions.cs | |
| parent | 1ecd35a3879bb5e8afd15f3e7ea22993c78f823d (diff) | |
| download | slskd-f5071fce7461949be7ffac129f283815a3ecd389.tar.gz | |
add Validation namespace and components
Diffstat (limited to 'src/slskd/Common/Validation/ValidationExtensions.cs')
| -rw-r--r-- | src/slskd/Common/Validation/ValidationExtensions.cs | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/slskd/Common/Validation/ValidationExtensions.cs b/src/slskd/Common/Validation/ValidationExtensions.cs new file mode 100644 index 00000000..511e1a31 --- /dev/null +++ b/src/slskd/Common/Validation/ValidationExtensions.cs @@ -0,0 +1,50 @@ +namespace slskd.Validation +{ + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Linq; + using slskd.Configuration; + + public static class ValidationExtensions + { + public static string GetResultView(this ValidationResult result) + { + return string.Join("\n", result.GetResultView(0)); + } + + public static IEnumerable<string> GetResultView(this ValidationResult result, int depth = 0) + { + var indent = new string(' ', depth * 2); + + if (result is CompositeValidationResult composite) + { + var lines = new[] { indent + result + ":" }.ToList(); + + foreach (var child in composite.Results) + { + lines.AddRange(child.GetResultView(depth + 1)); + } + + return lines; + } + else + { + return new[] { indent + result }; + } + } + + public static bool TryValidate(this Options options, out CompositeValidationResult result) + { + result = null; + var results = new List<ValidationResult>(); + + if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true)) + { + result = new CompositeValidationResult("Invalid configuration", results); + return false; + } + + return true; + } + } +} |
