/
ValidatorMapper.cs
77 lines (65 loc) · 3.08 KB
/
ValidatorMapper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using AzureFunctionsOpenApiFluentValidationExtensions.Rules;
using FluentValidation.Internal;
using FluentValidation.Validators;
namespace AzureFunctionsOpenApiFluentValidationExtensions;
internal class ValidatorMapper : IValidatorMapper
{
public bool TryMap(IRuleComponent component, [NotNullWhen(true)] out Rule? rule)
{
rule = component.Validator switch
{
INotEmptyValidator => NotEmptyRule.Instance,
INotNullValidator => NotNullRule.Instance,
IMaximumLengthValidator validator => new MaxLengthRule(Convert.ToInt32(validator.Max)),
IMinimumLengthValidator validator => new MinLengthRule(Convert.ToInt32(validator.Min)),
IExactLengthValidator validator => new ExactLengthRule(validator.Max),
ILengthValidator validator => new LengthRangeRule(validator.Min, validator.Max),
IRegularExpressionValidator validator => new RegularExpressionRule(validator.Expression),
IInclusiveBetweenValidator validator => new InclusiveBetweenRule((int)validator.From, (int)validator.To),
IBetweenValidator validator => new ExclusiveBetweenRule((int)validator.From, (int)validator.To),
IGreaterThanOrEqualValidator validator => new GreaterThanOrEqualRule(Convert.ToInt32(validator.ValueToCompare)),
ILessThanOrEqualValidator validator => new LessThanOrEqualRule(Convert.ToInt32(validator.ValueToCompare)),
IComparisonValidator validator => SetIComparisonValidatorRules(validator),
IPropertyValidator validator => SetIPropertyValidatorRules(validator),
_ => null
};
return rule is not null;
}
private static Rule? SetIComparisonValidatorRules(IComparisonValidator validator)
{
var type = validator.GetType();
if (!type.IsGenericType) return null;
if (type.GetGenericTypeDefinition() == typeof(GreaterThanValidator<,>))
{
var valueToCompare = validator.ValueToCompare;
if (valueToCompare is int value)
{
return new GreaterThanRule(value);
}
}
else if (type.GetGenericTypeDefinition() == typeof(LessThanValidator<,>))
{
var valueToCompare = validator.ValueToCompare;
if (valueToCompare is int value)
{
return new LessThanRule(value);
}
}
return null;
}
private static Rule? SetIPropertyValidatorRules(IPropertyValidator validator)
{
var type = validator.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ScalePrecisionValidator<>))
{
if (type.GetProperty(nameof(ScalePrecisionValidator<object>.Scale))?.GetValue(validator) is int scale
&& type.GetProperty(nameof(ScalePrecisionValidator<object>.Precision))?.GetValue(validator) is int precision)
{
return new ScalePrecisionRule(scale, precision);
}
}
return null;
}
}