#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
///
/// Provides options validation for a specific options type using the validation framework.
///
/// The type of options being validated.
public class ValidationOptions : IValidateOptions where TOptions : class
{
private readonly IValidator _validator;
///
/// Gets the name of the options being validated.
///
public string? Name { get; }
///
/// Initializes a new instance of the class.
///
/// The name of the options being validated. This can be .
/// The validator instance used to validate the options.
public ValidationOptions(string? name, IValidator validator)
{
Name = name;
_validator = validator;
}
///
/// Validates the specified .
///
/// The name of the options instance being validated.
/// The options instance to validate.
/// A that indicates whether the validation was successful or not.
public ValidateOptionsResult Validate(string? name, TOptions options)
{
// check if the name of the options is specified and matches the provided one
if (Name is not null && Name != name)
return ValidateOptionsResult.Skip;
ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null
List validationResult = _validator.Validate(options); // validate the options using the validator
// return a response based on the validation result
if (validationResult.Count == 0)
return ValidateOptionsResult.Success;
// if the validation fails, collect the error messages
string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")];
// and return them with a failure result
return ValidateOptionsResult.Fail(errors);
}
}