Skip to content

Commit

Permalink
Cleanup non-generic Validate overloads.
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremySkinner committed Feb 13, 2020
1 parent cb01931 commit dc1e2fc
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 43 deletions.
70 changes: 30 additions & 40 deletions src/FluentValidation/AbstractValidator.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation
#endregion

Expand Down Expand Up @@ -45,33 +45,23 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
get => _cascadeMode();
set => _cascadeMode = () => value;
}

ValidationResult IValidator.Validate(object instance) {
instance.Guard("Cannot pass null to Validate.", nameof(instance));
if(! ((IValidator)this).CanValidateInstancesOfType(instance.GetType())) {
throw new InvalidOperationException($"Cannot validate instances of type '{instance.GetType().Name}'. This validator can only validate instances of type '{typeof(T).Name}'.");
}

return Validate((T)instance);
return ((IValidator) this).Validate(new ValidationContext(instance));
}

Task<ValidationResult> IValidator.ValidateAsync(object instance, CancellationToken cancellation) {
instance.Guard("Cannot pass null to Validate.", nameof(instance));
if (!((IValidator) this).CanValidateInstancesOfType(instance.GetType())) {
throw new InvalidOperationException($"Cannot validate instances of type '{instance.GetType().Name}'. This validator can only validate instances of type '{typeof(T).Name}'.");
}

return ValidateAsync((T) instance, cancellation);
Task<ValidationResult> IValidator.ValidateAsync(object instance, CancellationToken cancellation) {
return ((IValidator)this).ValidateAsync(new ValidationContext(instance), cancellation);
}

ValidationResult IValidator.Validate(ValidationContext context) {
context.Guard("Cannot pass null to Validate", nameof(context));
return Validate(context.ToGeneric<T>());
return Validate(ValidationContext<T>.GetFromNonGenericContext(context));
}

Task<ValidationResult> IValidator.ValidateAsync(ValidationContext context, CancellationToken cancellation) {
context.Guard("Cannot pass null to Validate", nameof(context));
return ValidateAsync(context.ToGeneric<T>(), cancellation);
return ValidateAsync(ValidationContext<T>.GetFromNonGenericContext(context), cancellation);
}

/// <summary>
Expand All @@ -92,7 +82,7 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
public Task<ValidationResult> ValidateAsync(T instance, CancellationToken cancellation = new CancellationToken()) {
return ValidateAsync(new ValidationContext<T>(instance, new PropertyChain(), ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory()), cancellation);
}

/// <summary>
/// Validates the specified instance.
/// </summary>
Expand All @@ -103,15 +93,15 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat

var result = new ValidationResult();
bool shouldContinue = PreValidate(context, result);

if (!shouldContinue) {
return result;
}

EnsureInstanceNotNull(context.InstanceToValidate);

var failures = Rules.SelectMany(x => x.Validate(context));

foreach (var validationFailure in failures.Where(failure => failure != null)) {
result.Errors.Add(validationFailure);
}
Expand All @@ -132,9 +122,9 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
context.RootContextData["__FV_IsAsyncExecution"] = true;

var result = new ValidationResult();

bool shouldContinue = PreValidate(context, result);

if (!shouldContinue) {
return result;
}
Expand All @@ -149,7 +139,7 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
result.Errors.Add(failure);
}
}

SetExecutedRulesets(result, context);

return result;
Expand Down Expand Up @@ -210,7 +200,7 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
AddRule(rule);
var ruleBuilder = new RuleBuilder<T, TProperty>(rule, this);
return ruleBuilder;
}
}

/// <summary>
/// Defines a RuleSet that can be used to group together several validators.
Expand Down Expand Up @@ -239,7 +229,7 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
public IConditionBuilder When(Func<T, bool> predicate, Action action) {
return new ConditionBuilder<T>(Rules).When(predicate, action);
}

/// <summary>
/// Defines an inverse condition that applies to several rules
/// </summary>
Expand Down Expand Up @@ -276,7 +266,7 @@ public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidat
var rule = IncludeRule.Create<T>(rulesToInclude, () => CascadeMode);
AddRule(rule);
}

/// <summary>
/// Includes the rules from the specified validator
/// </summary>
Expand Down
14 changes: 11 additions & 3 deletions src/FluentValidation/ValidationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,20 +91,28 @@ public ValidationContext(T instanceToValidate, PropertyChain propertyChain, IVal
return context.ToGeneric<T>();
}

throw new NotSupportedException("context.InstanceToValidate is not of type " + typeof(T).FullName);
if (context.InstanceToValidate == null) {
return new ValidationContext<T>(default, context.PropertyChain, context.Selector) {
IsChildContext = context.IsChildContext,
RootContextData = context.RootContextData,
_parentContext = ((IValidationContext)context).ParentContext
};
}

throw new InvalidOperationException($"Cannot validate instances of type '{context.InstanceToValidate.GetType().Name}'. This validator can only validate instances of type '{typeof(T).Name}'.");
}
}

/// <summary>
/// Validation context
/// </summary>
public class ValidationContext : IValidationContext {
private IValidationContext _parentContext;
private protected IValidationContext _parentContext;

/// <summary>
/// Additional data associated with the validation request.
/// </summary>
public IDictionary<string, object> RootContextData { get; private set; } = new Dictionary<string, object>();
public IDictionary<string, object> RootContextData { get; private protected set; } = new Dictionary<string, object>();

/// <summary>
/// Creates a new validation context
Expand Down

0 comments on commit dc1e2fc

Please sign in to comment.