generated from Avanade/avanade-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWhenClause.cs
50 lines (43 loc) · 2.47 KB
/
WhenClause.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
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/CoreEx
using System;
namespace CoreEx.Validation.Clauses
{
/// <summary>
/// Represents a when test clause; in that the condition must be <c>true</c> to continue.
/// </summary>
/// <typeparam name="TEntity">The entity <see cref="Type"/>.</typeparam>
/// <typeparam name="TProperty">The property <see cref="Type"/>.</typeparam>
public class WhenClause<TEntity, TProperty> : IPropertyRuleClause<TEntity, TProperty> where TEntity : class
{
private readonly Predicate<TEntity>? _entityPredicate;
private readonly Predicate<TProperty>? _propertyPredicate;
private readonly Func<bool>? _when;
/// <summary>
/// Initializes a new instance of the <see cref="WhenClause{TEntity, TProperty}"/> class with a <paramref name="predicate"/> being passed the <typeparamref name="TEntity"/>.
/// </summary>
/// <param name="predicate">The when predicate.</param>
public WhenClause(Predicate<TEntity> predicate) => _entityPredicate = predicate.ThrowIfNull(nameof(predicate));
/// <summary>
/// Initializes a new instance of the <see cref="WhenClause{TEntity, TProperty}"/> class with a <paramref name="when"/> function.
/// </summary>
/// <param name="when">The when function.</param>
public WhenClause(Func<bool> when) => _when = when.ThrowIfNull(nameof(when));
/// <summary>
/// Initializes a new instance of the <see cref="WhenClause{TEntity, TProperty}"/> class with a <paramref name="predicate"/> being passed the <typeparamref name="TProperty"/>.
/// </summary>
/// <param name="predicate">The when predicate.</param>
public WhenClause(Predicate<TProperty> predicate) => _propertyPredicate = predicate.ThrowIfNull(nameof(predicate));
/// <summary>
/// Checks the clause.
/// </summary>
/// <param name="context">The <see cref="PropertyContext{TEntity, TProperty}"/>.</param>
/// <returns><c>true</c> where validation is to continue; otherwise, <c>false</c> to stop.</returns>
public bool Check(IPropertyContext context)
{
context.ThrowIfNull(nameof(context));
return _when != null ? _when.Invoke()
: _entityPredicate != null ? _entityPredicate.Invoke((TEntity)context.Parent.Value!)
: _propertyPredicate!.Invoke((TProperty)context.Value!);
}
}
}