github.com/go-email-validator/go-email-validator@v0.0.0-20230409163946-b8b9e6a0552e/pkg/ev/decorator_warnings.go (about)

     1  package ev
     2  
     3  import (
     4  	"github.com/emirpasic/gods/sets"
     5  )
     6  
     7  // NewWarningsDecorator creates warning decorator to skip some errors
     8  func NewWarningsDecorator(validator Validator, isWarning IsWarning) Validator {
     9  	return warningsDecorator{validator, isWarning}
    10  }
    11  
    12  // IsWarning is type to detect error as warning
    13  type IsWarning func(err error) bool
    14  
    15  // WarningSet is alias for sets.Set
    16  type WarningSet sets.Set
    17  
    18  // NewIsWarning creates function for detection of warnings
    19  func NewIsWarning(warningMap WarningSet, isWarning func(warningMap WarningSet) IsWarning) IsWarning {
    20  	return isWarning(warningMap)
    21  }
    22  
    23  type warningsDecorator struct {
    24  	validator Validator
    25  	isWarning IsWarning
    26  }
    27  
    28  func (w warningsDecorator) GetDeps() []ValidatorName {
    29  	return w.validator.GetDeps()
    30  }
    31  
    32  func (w warningsDecorator) Validate(input Input, results ...ValidationResult) ValidationResult {
    33  	result := w.validator.Validate(input, results...)
    34  	changeableResult, ok := result.(ChangeableValidationResult)
    35  	if !ok {
    36  		return result
    37  	}
    38  
    39  	var errors, warnings []error
    40  	for _, err := range result.Errors() {
    41  		if w.isWarning(err) {
    42  			warnings = append(warnings, err)
    43  		} else {
    44  			errors = append(errors, err)
    45  		}
    46  	}
    47  
    48  	changeableResult.SetErrors(errors)
    49  	changeableResult.SetWarnings(warnings)
    50  
    51  	return changeableResult.(ValidationResult)
    52  }