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

     1  package converter
     2  
     3  import (
     4  	"github.com/go-email-validator/go-email-validator/pkg/ev"
     5  	"github.com/go-email-validator/go-email-validator/pkg/ev/evmail"
     6  	"time"
     7  )
     8  
     9  // Name of converter
    10  type Name string
    11  
    12  // Options changes the process of converting
    13  type Options interface {
    14  	IsOptions()
    15  	ExecutedTime() time.Duration
    16  }
    17  
    18  // NewOptions creates Options
    19  func NewOptions(executedTime time.Duration) Options {
    20  	return options{
    21  		ExecutedTimeValue: executedTime,
    22  	}
    23  }
    24  
    25  type options struct {
    26  	ExecutedTimeValue time.Duration
    27  }
    28  
    29  func (options) IsOptions() {}
    30  func (o options) ExecutedTime() time.Duration {
    31  	return o.ExecutedTimeValue
    32  }
    33  
    34  // Interface converts ev.ValidationResult in some presenter
    35  type Interface interface {
    36  	// Can defines the possibility applying of a converter
    37  	Can(email evmail.Address, result ev.ValidationResult, opts Options) bool
    38  	// Convert converts ev.ValidationResult in some presenter
    39  	Convert(email evmail.Address, result ev.ValidationResult, opts Options) interface{}
    40  }
    41  
    42  // MapConverters is a map of converters
    43  type MapConverters map[ev.ValidatorName]Interface
    44  
    45  // NewCompositeConverter creates CompositeConverter
    46  func NewCompositeConverter(converters MapConverters) CompositeConverter {
    47  	return CompositeConverter{converters}
    48  }
    49  
    50  // CompositeConverter converts ev.ValidationResult depends of ev.ValidationResult.ValidatorName()
    51  type CompositeConverter struct {
    52  	converters MapConverters
    53  }
    54  
    55  func (p CompositeConverter) converter(email evmail.Address, result ev.ValidationResult, opts Options) Interface {
    56  	if converter, ok := p.converters[result.ValidatorName()]; ok && converter.Can(email, result, opts) {
    57  		return converter
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  // Can result ev.ValidationResult be converted
    64  func (p CompositeConverter) Can(email evmail.Address, result ev.ValidationResult, opts Options) bool {
    65  	return p.converter(email, result, opts) != nil
    66  }
    67  
    68  // Convert ev.ValidationResult depends of ev.ValidationResult.ValidatorName()
    69  func (p CompositeConverter) Convert(email evmail.Address, result ev.ValidationResult, opts Options) interface{} {
    70  	return p.converter(email, result, opts).Convert(email, result, opts)
    71  }