-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
gvalid_validator_check_struct.go
342 lines (328 loc) · 10.5 KB
/
gvalid_validator_check_struct.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gvalid
import (
"context"
"reflect"
"strings"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/internal/empty"
"github.com/gogf/gf/v2/os/gstructs"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gmeta"
"github.com/gogf/gf/v2/util/gutil"
)
func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error {
var (
errorMaps = make(map[string]map[string]error) // Returning error.
fieldToAliasNameMap = make(map[string]string) // Field names to alias name map.
resultSequenceRules = make([]fieldRule, 0)
isEmptyData = empty.IsEmpty(v.data)
isEmptyAssoc = empty.IsEmpty(v.assoc)
)
fieldMap, err := gstructs.FieldMap(gstructs.FieldMapInput{
Pointer: object,
PriorityTagArray: aliasNameTagPriority,
RecursiveOption: gstructs.RecursiveOptionEmbedded,
})
if err != nil {
return newValidationErrorByStr(internalObjectErrRuleName, err)
}
// It here must use gstructs.TagFields not gstructs.FieldMap to ensure error sequence.
tagFields, err := gstructs.TagFields(object, structTagPriority)
if err != nil {
return newValidationErrorByStr(internalObjectErrRuleName, err)
}
// If there's no struct tag and validation rules, it does nothing and returns quickly.
if len(tagFields) == 0 && v.messages == nil && isEmptyData && isEmptyAssoc {
return nil
}
var (
inputParamMap map[string]interface{}
checkRules = make([]fieldRule, 0)
nameToRuleMap = make(map[string]string) // just for internally searching index purpose.
customMessage = make(CustomMsg) // Custom rule error message map.
checkValueData = v.assoc // Ready to be validated data, which can be type of .
)
if checkValueData == nil {
checkValueData = object
}
switch assertValue := v.rules.(type) {
// Sequence tag: []sequence tag
// Sequence has order for error results.
case []string:
for _, tag := range assertValue {
name, rule, msg := ParseTagValue(tag)
if len(name) == 0 {
continue
}
if len(msg) > 0 {
var (
msgArray = strings.Split(msg, "|")
ruleArray = strings.Split(rule, "|")
)
for k, ruleKey := range ruleArray {
// If length of custom messages is lesser than length of rules,
// the rest rules use the default error messages.
if len(msgArray) <= k {
continue
}
if len(msgArray[k]) == 0 {
continue
}
array := strings.Split(ruleKey, ":")
if _, ok := customMessage[name]; !ok {
customMessage[name] = make(map[string]string)
}
customMessage[name].(map[string]string)[strings.TrimSpace(array[0])] = strings.TrimSpace(msgArray[k])
}
}
nameToRuleMap[name] = rule
checkRules = append(checkRules, fieldRule{
Name: name,
Rule: rule,
})
}
// Map type rules does not support sequence.
// Format: map[key]rule
case map[string]string:
nameToRuleMap = assertValue
for name, rule := range assertValue {
checkRules = append(checkRules, fieldRule{
Name: name,
Rule: rule,
})
}
}
// If there's no struct tag and validation rules, it does nothing and returns quickly.
if len(tagFields) == 0 && len(checkRules) == 0 && isEmptyData && isEmptyAssoc {
return nil
}
// Input parameter map handling.
if v.assoc == nil || !v.useAssocInsteadOfObjectAttributes {
inputParamMap = make(map[string]interface{})
} else {
inputParamMap = gconv.Map(v.assoc)
}
// Checks and extends the parameters map with struct alias tag.
if !v.useAssocInsteadOfObjectAttributes {
for nameOrTag, field := range fieldMap {
inputParamMap[nameOrTag] = field.Value.Interface()
if nameOrTag != field.Name() {
inputParamMap[field.Name()] = field.Value.Interface()
}
}
}
// Merge the custom validation rules with rules in struct tag.
// The custom rules has the most high priority that can overwrite the struct tag rules.
for _, field := range tagFields {
var (
isMeta bool
fieldName = field.Name() // Attribute name.
name, rule, msg = ParseTagValue(field.TagValue) // The `name` is different from `attribute alias`, which is used for validation only.
)
if len(name) == 0 {
if value, ok := fieldToAliasNameMap[fieldName]; ok {
// It uses alias name of the attribute if its alias name tag exists.
name = value
} else {
// It or else uses the attribute name directly.
name = fieldName
}
} else {
// It uses the alias name from validation rule.
fieldToAliasNameMap[fieldName] = name
}
// It here extends the params map using alias names.
// Note that the variable `name` might be alias name or attribute name.
if _, ok := inputParamMap[name]; !ok {
if !v.useAssocInsteadOfObjectAttributes {
inputParamMap[name] = field.Value.Interface()
} else {
if name != fieldName {
if foundKey, foundValue := gutil.MapPossibleItemByKey(inputParamMap, fieldName); foundKey != "" {
inputParamMap[name] = foundValue
}
}
}
}
if _, ok := nameToRuleMap[name]; !ok {
if _, ok = nameToRuleMap[fieldName]; ok {
// If there's alias name,
// use alias name as its key and remove the field name key.
nameToRuleMap[name] = nameToRuleMap[fieldName]
delete(nameToRuleMap, fieldName)
for index, checkRuleItem := range checkRules {
if fieldName == checkRuleItem.Name {
checkRuleItem.Name = name
checkRules[index] = checkRuleItem
break
}
}
} else {
nameToRuleMap[name] = rule
if fieldValue := field.Value.Interface(); fieldValue != nil {
_, isMeta = fieldValue.(gmeta.Meta)
}
checkRules = append(checkRules, fieldRule{
Name: name,
Rule: rule,
IsMeta: isMeta,
FieldKind: field.OriginalKind(),
})
}
} else {
// The input rules can overwrite the rules in struct tag.
continue
}
if len(msg) > 0 {
var (
msgArray = strings.Split(msg, "|")
ruleArray = strings.Split(rule, "|")
)
for k, ruleKey := range ruleArray {
// If length of custom messages is lesser than length of rules,
// the rest rules use the default error messages.
if len(msgArray) <= k {
continue
}
if len(msgArray[k]) == 0 {
continue
}
array := strings.Split(ruleKey, ":")
if _, ok := customMessage[name]; !ok {
customMessage[name] = make(map[string]string)
}
customMessage[name].(map[string]string)[strings.TrimSpace(array[0])] = strings.TrimSpace(msgArray[k])
}
}
}
// Custom error messages,
// which have the most priority than `rules` and struct tag.
if msg, ok := v.messages.(CustomMsg); ok && len(msg) > 0 {
for k, msgName := range msg {
if a, ok := fieldToAliasNameMap[k]; ok {
// Overwrite the key of field name.
customMessage[a] = msgName
} else {
customMessage[k] = msgName
}
}
}
// Temporary variable for value.
var value interface{}
// It checks the struct recursively if its attribute is a struct/struct slice.
for _, field := range fieldMap {
// No validation interface implements check.
if _, ok := field.Value.Interface().(iNoValidation); ok {
continue
}
// No validation field tag check.
if _, ok := field.TagLookup(noValidationTagName); ok {
continue
}
if field.IsEmbedded() {
if err = v.doCheckStruct(ctx, field.Value); err != nil {
// It merges the errors into single error map.
for k, m := range err.(*validationError).errors {
errorMaps[k] = m
}
}
} else {
if field.TagValue != "" {
fieldToAliasNameMap[field.Name()] = field.TagValue
}
switch field.OriginalKind() {
case reflect.Map, reflect.Struct, reflect.Slice, reflect.Array:
// Recursively check attribute slice/map.
_, value = gutil.MapPossibleItemByKey(inputParamMap, field.Name())
v.doCheckValueRecursively(ctx, doCheckValueRecursivelyInput{
Value: value,
Kind: field.OriginalKind(),
Type: field.Type().Type,
ErrorMaps: errorMaps,
ResultSequenceRules: &resultSequenceRules,
})
}
}
if v.bail && len(errorMaps) > 0 {
break
}
}
if v.bail && len(errorMaps) > 0 {
return newValidationError(gcode.CodeValidationFailed, resultSequenceRules, errorMaps)
}
// The following logic is the same as some of CheckMap but with sequence support.
for _, checkRuleItem := range checkRules {
if !checkRuleItem.IsMeta {
_, value = gutil.MapPossibleItemByKey(inputParamMap, checkRuleItem.Name)
if value == nil {
if aliasName := fieldToAliasNameMap[checkRuleItem.Name]; aliasName != "" {
_, value = gutil.MapPossibleItemByKey(inputParamMap, aliasName)
}
}
}
// Empty json string checks according to mapping field kind.
if value != nil {
switch checkRuleItem.FieldKind {
case reflect.Struct, reflect.Map:
if gconv.String(value) == emptyJsonObjectStr {
value = ""
}
case reflect.Slice, reflect.Array:
if gconv.String(value) == emptyJsonArrayStr {
value = ""
}
}
}
// It checks each rule and its value in loop.
if validatedError := v.doCheckValue(ctx, doCheckValueInput{
Name: checkRuleItem.Name,
Value: value,
Rule: checkRuleItem.Rule,
Messages: customMessage[checkRuleItem.Name],
DataRaw: checkValueData,
DataMap: inputParamMap,
}); validatedError != nil {
_, errorItem := validatedError.FirstItem()
// ============================================================
// Only in map and struct validations:
// If value is nil or empty string and has no required* rules,
// it clears the error message.
// ============================================================
if !checkRuleItem.IsMeta && (value == nil || gconv.String(value) == "") {
required := false
// rule => error
for ruleKey := range errorItem {
if required = v.checkRuleRequired(ruleKey); required {
break
}
}
if !required {
continue
}
}
if _, ok := errorMaps[checkRuleItem.Name]; !ok {
errorMaps[checkRuleItem.Name] = make(map[string]error)
}
for ruleKey, errorItemMsgMap := range errorItem {
errorMaps[checkRuleItem.Name][ruleKey] = errorItemMsgMap
}
// Bail feature.
if v.bail {
break
}
}
}
if len(errorMaps) > 0 {
return newValidationError(
gcode.CodeValidationFailed,
append(checkRules, resultSequenceRules...),
errorMaps,
)
}
return nil
}