Files
kreta/Kreta.WebApi/Ellenorzo/Kreta.Ellenorzo.BL/VN/Logic/ValidatorLogic.cs
T
2024-03-13 00:33:46 +01:00

72 lines
2.5 KiB
C#

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Kreta.Core;
using Kreta.Core.Domain;
using Kreta.Core.Enum;
using Kreta.Core.Exceptions;
namespace Kreta.Ellenorzo.BL.VN.Logic
{
/// <summary>
/// Author: Kovács Kornél (DevKornél) Created On: 2019.06.
/// Validates the models with "DataAnnotationAttributes" and gives You the option
/// to create custom validation if model implements the "IValidatableObject" interface.
/// </summary>
internal class ValidatorLogic
{
private readonly List<ValidationResult> _errorList = new List<ValidationResult>();
private readonly bool _isValid = true;
internal ValidatorLogic(object instance)
{
var context = new ValidationContext(instance, serviceProvider: null, items: null);
_isValid = Validator.TryValidateObject(instance, context, _errorList, true);
}
internal ValidatorLogic(IEnumerable<object> instance)
{
foreach (var item in instance)
{
var context = new ValidationContext(item, serviceProvider: null, items: null);
if (!Validator.TryValidateObject(item, context, _errorList, true))
{
_isValid = false;
}
}
}
public static implicit operator string(ValidatorLogic validator) => validator.GetFirstUserFriendlyError();
internal BlException ConvertToValidationException()
{
var exception = new BlException(BlExceptionType.ModelValidacio);
var count = 1;
foreach (var error in _errorList)
{
var name = error.MemberNames.FirstOrDefault() ?? "custom_" + count;
exception.ErrorList.Add(new DetailedErrorItem(name, error.ErrorMessage, BlExceptionType.ModelValidacio));
count++;
}
return exception;
}
internal string GetFirstUserFriendlyError()
=> _errorList.Count > 0 ? _errorList[0].ErrorMessage : string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal string GetUserFriendlyError()
=> string.Join(Constants.General.LineSeparator, _errorList.Select(x => x.ErrorMessage).ToArray());
internal void ThrowExceptionIfModelIsNotvalid()
{
if (!_isValid)
{
throw ConvertToValidationException();
}
}
}
}