| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ValidationBehavior.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections; |
| | | 9 | | using System.Collections.Generic; |
| | | 10 | | using System.ComponentModel; |
| | | 11 | | using System.Diagnostics.CodeAnalysis; |
| | | 12 | | using System.Linq; |
| | | 13 | | using FluentValidation; |
| | | 14 | | using FluentValidation.Internal; |
| | | 15 | | using FluentValidation.Results; |
| | | 16 | | using MyNet.Metadata; |
| | | 17 | | using MyNet.Observable.Behaviors.Metadata.Features; |
| | | 18 | | |
| | | 19 | | namespace MyNet.Observable.Behaviors; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Provides validation support for an ObservableObject. |
| | | 23 | | /// </summary> |
| | 81 | 24 | | public sealed class ValidationBehavior<T>(T owner, IValidator validator) : SuspendableBehavior<T>(owner), IPropertyChang |
| | | 25 | | where T : ObservableObject |
| | | 26 | | { |
| | 81 | 27 | | private readonly Dictionary<string, List<string>> _errors = []; |
| | | 28 | | |
| | | 29 | | #region INotifyDataErrorInfo |
| | | 30 | | |
| | | 31 | | /// <inheritdoc/> |
| | 39 | 32 | | public bool HasErrors => _errors.Count > 0; |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Gets all validation errors for the object. This property returns an enumerable collection of all validation erro |
| | | 36 | | /// </summary> |
| | | 37 | | [SuppressMessage("Naming", "CA1721:Property names should not match get methods", Justification = "Conforms to INotif |
| | 18 | 38 | | public IReadOnlyCollection<string> Errors => [.. _errors.Values.SelectMany(x => x).Distinct()]; |
| | | 39 | | |
| | | 40 | | /// <inheritdoc /> |
| | | 41 | | public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged; |
| | | 42 | | |
| | | 43 | | /// <inheritdoc /> |
| | | 44 | | public IEnumerable GetErrors(string? propertyName) |
| | 0 | 45 | | => string.IsNullOrWhiteSpace(propertyName) |
| | 0 | 46 | | ? _errors.SelectMany(x => x.Value) |
| | 0 | 47 | | : (IEnumerable)(_errors.TryGetValue(propertyName, out var list) |
| | 0 | 48 | | ? list |
| | 0 | 49 | | : []); |
| | | 50 | | |
| | | 51 | | #endregion |
| | | 52 | | |
| | | 53 | | #region Validation |
| | | 54 | | |
| | | 55 | | /// <inheritdoc/> |
| | | 56 | | public bool Validate() |
| | | 57 | | { |
| | 30 | 58 | | if (IsDisposed) |
| | 0 | 59 | | return false; |
| | | 60 | | |
| | 30 | 61 | | if (IsSuspended) |
| | 0 | 62 | | return true; |
| | | 63 | | |
| | 30 | 64 | | var context = CreateValidationContext(); |
| | | 65 | | |
| | 30 | 66 | | var result = validator.Validate(context); |
| | | 67 | | |
| | 30 | 68 | | ApplyValidationResult(result); |
| | | 69 | | |
| | 30 | 70 | | return !HasErrors; |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | /// <inheritdoc/> |
| | | 74 | | public void ValidateProperty(string propertyName) |
| | | 75 | | { |
| | 309 | 76 | | if (IsDisposed) |
| | 0 | 77 | | return; |
| | | 78 | | |
| | 309 | 79 | | if (IsSuspended) |
| | 0 | 80 | | return; |
| | | 81 | | |
| | 309 | 82 | | var selector = new MemberNameValidatorSelector([propertyName]); |
| | 309 | 83 | | var context = CreateValidationContext(selector); |
| | 309 | 84 | | var result = validator.Validate(context); |
| | | 85 | | |
| | 309 | 86 | | ApplyPropertyValidationResult(propertyName, result); |
| | 309 | 87 | | } |
| | | 88 | | |
| | | 89 | | /// <summary> |
| | | 90 | | /// Resets the validation state of the object by clearing all validation errors. This method clears the internal dic |
| | | 91 | | /// </summary> |
| | | 92 | | public void ResetValidation() |
| | | 93 | | { |
| | 0 | 94 | | if (_errors.Count == 0) |
| | 0 | 95 | | return; |
| | | 96 | | |
| | 0 | 97 | | var properties = _errors.Keys.ToArray(); |
| | | 98 | | |
| | 0 | 99 | | _errors.Clear(); |
| | | 100 | | |
| | 0 | 101 | | RaiseValidationStateChanged(); |
| | | 102 | | |
| | 0 | 103 | | foreach (var property in properties) |
| | | 104 | | { |
| | 0 | 105 | | ErrorsChanged?.Invoke(Owner, new(property)); |
| | | 106 | | } |
| | 0 | 107 | | } |
| | | 108 | | |
| | | 109 | | #endregion |
| | | 110 | | |
| | | 111 | | #region Property behavior |
| | | 112 | | |
| | | 113 | | /// <inheritdoc /> |
| | | 114 | | public void OnPropertyChanged(PropertyMutationContext context) |
| | | 115 | | { |
| | 279 | 116 | | if (IsDisposed || IsSuspended) |
| | 0 | 117 | | return; |
| | | 118 | | |
| | 279 | 119 | | if (string.IsNullOrWhiteSpace(context.PropertyName)) |
| | 0 | 120 | | return; |
| | | 121 | | |
| | 279 | 122 | | ValidateProperty(context.PropertyName); |
| | | 123 | | |
| | 570 | 124 | | foreach (var dependent in GetDependents(context.PropertyName)) |
| | | 125 | | { |
| | 6 | 126 | | ValidateProperty(dependent); |
| | | 127 | | } |
| | 279 | 128 | | } |
| | | 129 | | |
| | | 130 | | #endregion |
| | | 131 | | |
| | | 132 | | #region Internal validation |
| | | 133 | | |
| | | 134 | | /// <summary> |
| | | 135 | | /// Creates a validation context for the owner object. This method creates a validation context that is used when pe |
| | | 136 | | /// </summary> |
| | | 137 | | /// <param name="selector">The validator selector to use, or null to use the default selector.</param> |
| | | 138 | | /// <returns>The validation context for the owner object.</returns> |
| | 339 | 139 | | private ValidationContext<T> CreateValidationContext(IValidatorSelector? selector = null) => new(Owner, new(), selec |
| | | 140 | | |
| | | 141 | | /// <summary> |
| | | 142 | | /// Applies the validation result for the entire object. This method takes the validation result for the entire obje |
| | | 143 | | /// </summary> |
| | | 144 | | /// <param name="result">The validation result for the entire object.</param> |
| | | 145 | | private void ApplyValidationResult(ValidationResult result) |
| | | 146 | | { |
| | 30 | 147 | | var previousProperties = _errors.Keys.ToArray(); |
| | | 148 | | |
| | 30 | 149 | | _errors.Clear(); |
| | | 150 | | |
| | 96 | 151 | | foreach (var group in result.Errors.GroupBy(x => x.PropertyName)) |
| | | 152 | | { |
| | 18 | 153 | | _errors[group.Key] = |
| | 18 | 154 | | [ |
| | 18 | 155 | | .. group |
| | 18 | 156 | | .Select(x => x.ErrorMessage) |
| | 18 | 157 | | .Distinct() |
| | 18 | 158 | | ]; |
| | | 159 | | |
| | 18 | 160 | | RaiseErrorsChanged(group.Key); |
| | | 161 | | } |
| | | 162 | | |
| | 78 | 163 | | foreach (var property in previousProperties) |
| | | 164 | | { |
| | 9 | 165 | | if (!_errors.ContainsKey(property)) |
| | 0 | 166 | | RaiseErrorsChanged(property); |
| | | 167 | | } |
| | | 168 | | |
| | 30 | 169 | | RaiseValidationStateChanged(); |
| | 30 | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary> |
| | | 173 | | /// Applies the validation result for a specific property. This method takes the validation result for a specific pr |
| | | 174 | | /// </summary> |
| | | 175 | | /// <param name="propertyName">The name of the property for which the validation result is being applied.</param> |
| | | 176 | | /// <param name="result">The validation result for the specified property.</param> |
| | | 177 | | private void ApplyPropertyValidationResult(string propertyName, ValidationResult result) |
| | | 178 | | { |
| | 309 | 179 | | var errors = |
| | 309 | 180 | | result.Errors |
| | 309 | 181 | | .Where(x => x.PropertyName == propertyName) |
| | 309 | 182 | | .Select(x => x.ErrorMessage) |
| | 309 | 183 | | .Distinct() |
| | 309 | 184 | | .ToList(); |
| | | 185 | | |
| | 309 | 186 | | if (errors.Count == 0) |
| | | 187 | | { |
| | 288 | 188 | | if (_errors.Remove(propertyName)) |
| | | 189 | | { |
| | 6 | 190 | | RaiseValidationStateChanged(); |
| | 6 | 191 | | RaiseErrorsChanged(propertyName); |
| | | 192 | | } |
| | | 193 | | |
| | 288 | 194 | | return; |
| | | 195 | | } |
| | | 196 | | |
| | 21 | 197 | | _errors[propertyName] = errors; |
| | | 198 | | |
| | 21 | 199 | | RaiseValidationStateChanged(); |
| | 21 | 200 | | RaiseErrorsChanged(propertyName); |
| | 21 | 201 | | } |
| | | 202 | | |
| | | 203 | | #endregion |
| | | 204 | | |
| | | 205 | | #region Notifications |
| | | 206 | | |
| | | 207 | | /// <summary> |
| | | 208 | | /// Raises notifications for changes in the validation state. This method is called whenever there is a change in th |
| | | 209 | | /// </summary> |
| | | 210 | | private void RaiseValidationStateChanged() |
| | | 211 | | { |
| | 57 | 212 | | Owner.NotifyPropertyChanged(nameof(HasErrors)); |
| | 57 | 213 | | Owner.NotifyPropertyChanged(nameof(Errors)); |
| | 57 | 214 | | } |
| | | 215 | | |
| | | 216 | | /// <summary> |
| | | 217 | | /// Raises the ErrorsChanged event for a specific property. This method is called whenever the validation errors for |
| | | 218 | | /// </summary> |
| | | 219 | | /// <param name="propertyName">The name of the property whose validation errors have changed.</param> |
| | 45 | 220 | | private void RaiseErrorsChanged(string propertyName) => ErrorsChanged?.Invoke(Owner, new(propertyName)); |
| | | 221 | | |
| | | 222 | | #endregion |
| | | 223 | | |
| | | 224 | | /// <inheritdoc/> |
| | | 225 | | protected override void DisposeManagedResources() |
| | | 226 | | { |
| | 3 | 227 | | _errors.Clear(); |
| | | 228 | | |
| | 3 | 229 | | base.DisposeManagedResources(); |
| | 3 | 230 | | } |
| | | 231 | | |
| | | 232 | | #region Helpers |
| | | 233 | | |
| | | 234 | | /// <summary> |
| | | 235 | | /// Gets the dependent properties for a given property. This method retrieves the dependent properties for a specifi |
| | | 236 | | /// </summary> |
| | | 237 | | /// <param name="propertyName">The name of the property whose dependent properties are to be retrieved.</param> |
| | | 238 | | /// <returns>An array of property names that are dependent on the specified property.</returns> |
| | 279 | 239 | | private string[] GetDependents(string propertyName) => MetadataRegistry.Get(Owner.GetType()).GetProperty(propertyNam |
| | 279 | 240 | | ? [.. feature.Dependents] |
| | 279 | 241 | | : []; |
| | | 242 | | |
| | | 243 | | #endregion |
| | | 244 | | } |
| | | 245 | | |