| | | 1 | | namespace Pozitron.QuerySpecification; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Validates specifications. |
| | | 5 | | /// </summary> |
| | | 6 | | public class SpecificationValidator |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Gets the default instance of the <see cref="SpecificationValidator"/> class. |
| | | 10 | | /// </summary> |
| | 2 | 11 | | public static SpecificationValidator Default = new(); |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Gets the list of validators. |
| | | 15 | | /// </summary> |
| | 8 | 16 | | protected List<IValidator> Validators { get; } |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Initializes a new instance of the <see cref="SpecificationValidator"/> class. |
| | | 20 | | /// </summary> |
| | 5 | 21 | | public SpecificationValidator() |
| | | 22 | | { |
| | 5 | 23 | | Validators = TypeDiscovery.IsAutoDiscoveryEnabled |
| | 5 | 24 | | ? TypeDiscovery.GetValidators() |
| | 5 | 25 | | : |
| | 5 | 26 | | [ |
| | 5 | 27 | | WhereValidator.Instance, |
| | 5 | 28 | | LikeValidator.Instance, |
| | 5 | 29 | | ]; |
| | 5 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Initializes a new instance of the <see cref="SpecificationValidator"/> class with the specified validators. |
| | | 34 | | /// </summary> |
| | | 35 | | /// <param name="validators">The validators to use.</param> |
| | 1 | 36 | | public SpecificationValidator(IEnumerable<IValidator> validators) |
| | | 37 | | { |
| | 1 | 38 | | Validators = validators.ToList(); |
| | 1 | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Determines whether the specified entity is valid according to the given specification. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <typeparam name="T">The type of the entity.</typeparam> |
| | | 45 | | /// <param name="entity">The entity to validate.</param> |
| | | 46 | | /// <param name="specification">The specification to evaluate.</param> |
| | | 47 | | /// <returns>true if the entity is valid; otherwise, false.</returns> |
| | | 48 | | public virtual bool IsValid<T>(T entity, Specification<T> specification) |
| | | 49 | | { |
| | 10 | 50 | | if (specification.IsEmpty) return true; |
| | | 51 | | |
| | 30 | 52 | | foreach (var validator in Validators) |
| | | 53 | | { |
| | 10 | 54 | | if (validator.IsValid(entity, specification) == false) |
| | 2 | 55 | | return false; |
| | | 56 | | } |
| | | 57 | | |
| | 4 | 58 | | return true; |
| | 2 | 59 | | } |
| | | 60 | | } |