2013-08-21 08:27:15 +02:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq.Expressions;
|
|
|
|
|
using FluentValidation;
|
|
|
|
|
using FluentValidation.Internal;
|
2013-08-21 21:08:03 +02:00
|
|
|
|
using FluentValidation.Resources;
|
2013-08-21 08:27:15 +02:00
|
|
|
|
using NzbDrone.Api.ClientSchema;
|
|
|
|
|
using System.Linq;
|
2013-04-21 00:14:41 +02:00
|
|
|
|
|
|
|
|
|
namespace NzbDrone.Api.REST
|
|
|
|
|
{
|
|
|
|
|
public class ResourceValidator<TResource> : AbstractValidator<TResource>
|
|
|
|
|
{
|
2013-08-21 21:08:03 +02:00
|
|
|
|
public IRuleBuilderInitial<TResource, TProperty> RuleForField<TProperty>(Expression<Func<TResource, IEnumerable<Field>>> fieldListAccessor, string fieldName)
|
2013-08-21 08:27:15 +02:00
|
|
|
|
{
|
2013-08-21 21:08:03 +02:00
|
|
|
|
var rule = new PropertyRule(fieldListAccessor.GetMember(), c => GetValue(c, fieldListAccessor.Compile(), fieldName), null, () => CascadeMode.Continue, typeof(TProperty), typeof(TResource));
|
2013-08-22 02:36:35 +02:00
|
|
|
|
rule.PropertyName = fieldName;
|
2013-08-21 21:08:03 +02:00
|
|
|
|
rule.DisplayName = new StaticStringSource(fieldName);
|
2013-04-21 00:14:41 +02:00
|
|
|
|
|
2013-08-21 08:27:15 +02:00
|
|
|
|
AddRule(rule);
|
|
|
|
|
return new RuleBuilder<TResource, TProperty>(rule);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static object GetValue(object container, Func<TResource, IEnumerable<Field>> fieldListAccessor, string fieldName)
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
var resource = fieldListAccessor((TResource)container).SingleOrDefault(c => c.Name == fieldName);
|
|
|
|
|
|
|
|
|
|
if (resource == null)
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return resource.Value;
|
|
|
|
|
}
|
2013-04-21 00:14:41 +02:00
|
|
|
|
}
|
|
|
|
|
}
|