Use MethodResolver in ValidateInputAttribute

This commit is contained in:
VladV 2022-05-09 15:12:30 +03:00
parent 7c1e995bdf
commit 682ed659db

View File

@ -1,6 +1,7 @@
using System;
using System.Reflection;
using TriInspector;
using TriInspector.Resolvers;
using TriInspector.Validators;
[assembly: RegisterTriAttributeValidator(typeof(ValidateInputValidator))]
@ -9,24 +10,28 @@ namespace TriInspector.Validators
{
public class ValidateInputValidator : TriAttributeValidator<ValidateInputAttribute>
{
private MethodResolver<TriValidationResult> _resolver;
public override void Initialize(TriPropertyDefinition propertyDefinition)
{
base.Initialize(propertyDefinition);
_resolver = MethodResolver.Resolve<TriValidationResult>(propertyDefinition, Attribute.Method);
}
public override TriValidationResult Validate(TriProperty property)
{
var methodName = Attribute.Method;
if (_resolver.TryGetErrorString(out var error))
{
return TriValidationResult.Error(error);
}
for (var targetIndex = 0; targetIndex < property.PropertyTree.TargetObjects.Length; targetIndex++)
{
var parentValue = property.Parent.GetValue(targetIndex);
var parentType = parentValue.GetType();
if (!TryFindValidationMethod(parentType, methodName, out var methodInfo))
{
return TriValidationResult.Error($"Method '{methodName}' not exists or has wrong signature");
}
TriValidationResult result;
try
{
result = (TriValidationResult) methodInfo.Invoke(parentValue, Array.Empty<object>());
result = _resolver.InvokeForTarget(property, targetIndex);
}
catch (Exception e)
{
@ -35,7 +40,7 @@ namespace TriInspector.Validators
e = targetInvocationException.InnerException;
}
result = TriValidationResult.Error($"Exception was thrown: {e}'");
result = TriValidationResult.Error($"Exception was thrown: {e}");
}
if (!result.IsValid)
@ -46,25 +51,5 @@ namespace TriInspector.Validators
return TriValidationResult.Valid;
}
private static bool TryFindValidationMethod(Type type, string method, out MethodInfo result)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
foreach (var methodInfo in type.GetMethods(flags))
{
if (methodInfo.Name == method &&
methodInfo.ReturnType == typeof(TriValidationResult) &&
methodInfo.GetParameters() is var parameterInfos &&
parameterInfos.Length == 0)
{
result = methodInfo;
return true;
}
}
result = default;
return false;
}
}
}