-
Notifications
You must be signed in to change notification settings - Fork 0
/
bool.go
88 lines (72 loc) · 1.49 KB
/
bool.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package buzz
import (
"fmt"
"reflect"
)
var (
boolReflectType = reflect.TypeOf(false)
)
type BuzzBoolValidateFunc func(bool) error
type BuzzBool struct {
name string
validateFuncs []BuzzBoolValidateFunc
}
func Bool() *BuzzBool {
return &BuzzBool{}
}
func (b *BuzzBool) Name() string {
return b.name
}
func (b *BuzzBool) Type() reflect.Type {
return boolReflectType
}
func (b *BuzzBool) Validate(v any) error {
vBool, ok := v.(bool)
if !ok {
return fmt.Errorf(invalidTypeMsg, boolReflectType, v)
}
errAggr := NewFieldErrorAggregator()
for _, valFn := range b.validateFuncs {
if err := valFn(vBool); err != nil {
if errAggr.Handle(err) != nil {
return err
}
}
}
return errAggr.OrNil()
}
func (b *BuzzBool) WithName(name string) BuzzField {
b.name = name
return b
}
func (b *BuzzBool) Clone() BuzzField {
return &BuzzBool{
name: b.name,
validateFuncs: b.validateFuncs,
}
}
func (b *BuzzBool) True() *BuzzBool {
b.registerValidateFunc(func(v bool) error {
if v {
return nil
}
return MakeFieldError(b.name, "True", "must be true")
})
return b
}
func (b *BuzzBool) False() *BuzzBool {
b.registerValidateFunc(func(v bool) error {
if !v {
return nil
}
return MakeFieldError(b.name, "False", "must be false")
})
return b
}
func (b *BuzzBool) Custom(fn BuzzBoolValidateFunc) *BuzzBool {
b.registerValidateFunc(fn)
return b
}
func (b *BuzzBool) registerValidateFunc(fn BuzzBoolValidateFunc) {
b.validateFuncs = append(b.validateFuncs, fn)
}