-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathValidationRule.cs
More file actions
77 lines (66 loc) · 2.28 KB
/
ValidationRule.cs
File metadata and controls
77 lines (66 loc) · 2.28 KB
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
77
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Validations
{
/// <summary>
/// Class containing validation rule logic.
/// </summary>
public abstract class ValidationRule
{
/// <summary>
/// Element Type.
/// </summary>
internal abstract Type ElementType { get; }
/// <summary>
/// Validation rule Name.
/// </summary>
public string Name { get; }
/// <summary>
/// Validate the object.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="item">The object item.</param>
internal abstract void Evaluate(IValidationContext context, object item);
internal ValidationRule(string name)
{
Name = !string.IsNullOrEmpty(name) ? name : throw new ArgumentNullException(nameof(name));
}
}
/// <summary>
/// Class containing validation rule logic for <see cref="IOpenApiElement"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ValidationRule<T> : ValidationRule
{
private readonly Action<IValidationContext, T> _validate;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRule"/> class.
/// </summary>
/// <param name="name">Validation rule name.</param>
/// <param name="validate">Action to perform the validation.</param>
public ValidationRule(string name, Action<IValidationContext, T> validate)
: base(name)
{
_validate = Utils.CheckArgumentNull(validate);
}
internal override Type ElementType
{
get { return typeof(T); }
}
internal override void Evaluate(IValidationContext context, object item)
{
if (item == null)
{
return;
}
if (item is not T typedItem)
{
throw new ArgumentException(string.Format(SRResource.InputItemShouldBeType, typeof(T).FullName));
}
this._validate(context, typedItem);
}
}
}