-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
to.go
49 lines (41 loc) · 1.38 KB
/
to.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package valis
import "github.com/soranoba/valis/code"
type (
ConvertFunc func(value interface{}) (interface{}, error)
)
type (
toRule struct {
convertFunc ConvertFunc
rules []Rule
}
toRuleErrorCollector struct {
ErrorCollector
loc *Location
value interface{}
}
)
// To returns a new rule that verifies the converted value met all rules and all common rules.
func To(convertFunc ConvertFunc, rules ...Rule) Rule {
return &toRule{convertFunc: convertFunc, rules: rules}
}
func (rule *toRule) Validate(validator *Validator, value interface{}) {
newValue, err := rule.convertFunc(value)
if err != nil {
validator.ErrorCollector().Add(validator.Location(), NewError(code.ConversionFailed, value, err))
return
}
errorCollector := newToRuleErrorCollector(validator.ErrorCollector(), validator.Location(), value)
newValidator := validator.Clone(&CloneOpts{InheritLocation: true, ErrorCollector: errorCollector})
And(rule.rules...).Validate(newValidator, newValue)
}
func newToRuleErrorCollector(errorCollector ErrorCollector, location *Location, value interface{}) ErrorCollector {
return &toRuleErrorCollector{ErrorCollector: errorCollector, loc: location, value: value}
}
func (c *toRuleErrorCollector) Add(loc *Location, err Error) {
if loc == c.loc {
newDetail := *err
newDetail.valueBeforeConversion = c.value
err = &newDetail
}
c.ErrorCollector.Add(loc, err)
}