-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpending.go
121 lines (95 loc) · 2.57 KB
/
pending.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package golidate
import (
"context"
"fmt"
"reflect"
)
type Pending struct {
value any
attribute string
rules []Rule
self bool
}
func pending(value any, self bool) Pending {
reflected := reflect.ValueOf(value)
if reflected.Kind() == reflect.Ptr && !reflected.IsNil() {
return Pending{
value: reflected.Elem().Interface(),
attribute: "",
rules: make([]Rule, 0),
self: self,
}
}
return Pending{
value: value,
attribute: "",
rules: make([]Rule, 0),
self: self,
}
}
func Value(value any) Pending {
return pending(value, false)
}
func Self(value any) Pending {
return pending(value, true)
}
func (pending Pending) Rules(rules ...Rule) Pending {
pending.rules = rules
return pending
}
func (pending Pending) AppendRules(rules ...Rule) Pending {
pending.rules = append(pending.rules, rules...)
return pending
}
func (pending Pending) Name(attribute string) Pending {
pending.attribute = attribute
return pending
}
func (pending Pending) attributeOfIndex(i int) string {
if pending.attribute == "" {
return fmt.Sprintf("%d", i)
}
return fmt.Sprintf("%s.%d", pending.attribute, i)
}
func (pending Pending) attributeOfKey(s string) string {
if pending.attribute == "" {
return s
}
return fmt.Sprintf("%s.%s", pending.attribute, s)
}
func (pending Pending) recursiveValidate(ctx context.Context) Results {
if validatable, ok := pending.value.(Validator); ok && !pending.self {
return validatable.Validate(ctx).Prefixed(pending.attribute)
}
results := make(Results, 0)
reflected := reflect.ValueOf(pending.value)
switch reflected.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < reflected.Len(); i++ {
if validatable, ok := reflected.Index(i).Interface().(Validator); ok {
name := pending.attributeOfIndex(i)
results = append(results, validatable.Validate(ctx).Prefixed(name)...)
}
}
case reflect.Map:
for _, key := range reflected.MapKeys() {
if validatable, ok := reflected.MapIndex(key).Interface().(Validator); ok {
name := pending.attributeOfKey(key.String())
results = append(results, validatable.Validate(ctx).Prefixed(name)...)
}
}
}
return results
}
func (pending Pending) Validate(ctx context.Context) Results {
results := make(Results, 0, len(pending.rules))
for _, rule := range pending.rules {
result := rule(pending.value)
if pending.attribute != "" {
result = result.Name(pending.attribute)
}
expanded := result.Results(pending.attribute)
results = append(results, expanded...)
}
return append(results, pending.recursiveValidate(ctx)...)
}