-
Notifications
You must be signed in to change notification settings - Fork 2
/
validator_for.go
293 lines (276 loc) · 8.69 KB
/
validator_for.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
package valix
import (
"errors"
"fmt"
"reflect"
"time"
)
const (
tagNameV8n = "v8n"
tagNameV8nAs = "v8n-as"
tagNameJson = "json"
)
const (
errMsgValidatorForStructOnly = "ValidatorFor can only be used with struct arg"
errMsgCannotFindPropertyInRepo = tagNameV8nAs + " tag cannot find property name '%s' in properties repository"
errMsgIncompatiblePropertyType = tagNameV8nAs + " tag has incompatible field type for property name '%s'"
)
// ValidatorFor creates a Validator for a specified struct
//
// # If a Validator cannot be compiled for the supplied struct an error is returned
//
// When evaluating the supplied struct to build a Validator, tags on the struct fields
// are used to further clarify the validation constraints. These are specified using the
// `v8n` tag (see full documentation for details of this tag)
//
// The `json` tag is also used, if specified, to determine the JSON property name to be used.
func ValidatorFor(vstruct interface{}, options ...Option) (*Validator, error) {
ty := reflect.TypeOf(vstruct)
if ty.Kind() != reflect.Struct {
return nil, errors.New(errMsgValidatorForStructOnly)
}
result, err := emptyValidatorFromOptions(options...)
if err != nil {
return nil, err
}
ignoreOas := false
for _, o := range options {
if _, ok := o.(*optionIgnoreOasTags); ok {
ignoreOas = true
break
}
}
properties, err := buildPropertyValidators(ty, ignoreOas)
if err != nil {
return nil, err
}
result.Properties = properties
return result, nil
}
// MustCompileValidatorFor creates a Validator for a specified struct
//
// Similar to ValidatorFor but rather than returning an error, it panics if a
// Validator cannot be compiled for the struct
func MustCompileValidatorFor(vstruct interface{}, options ...Option) *Validator {
v, err := ValidatorFor(vstruct, options...)
if err != nil {
panic(err)
}
return v
}
func emptyValidatorFromOptions(options ...Option) (*Validator, error) {
result := &Validator{
IgnoreUnknownProperties: false,
Properties: Properties{},
Constraints: nil,
AllowArray: false,
DisallowObject: false,
AllowNullJson: false,
UseNumber: false,
StopOnFirst: false,
}
for _, opt := range options {
if opt != nil {
if err := opt.Apply(result); err != nil {
return nil, err
}
}
}
return result, nil
}
func buildPropertyValidators(ty reflect.Type, ignoreOas bool) (Properties, error) {
cnt := ty.NumField()
result := make(Properties, cnt)
newTy := reflect.New(ty)
for i := 0; i < cnt; i++ {
fld := ty.Field(i)
actualFld := newTy.Elem().FieldByName(fld.Name)
if actualFld.CanSet() {
pv, fn, err := propertyValidatorFromField(fld, ignoreOas)
if err != nil {
return nil, err
}
result[fn] = pv
}
}
return result, nil
}
func propertyValidatorFromField(fld reflect.StructField, ignoreOas bool) (*PropertyValidator, string, error) {
name := getFieldName(fld)
result, err := initialPropertyValidator(fld, name)
if err != nil {
return nil, name, err
}
if err := result.processV8nTag(fld.Name, name, fld); err != nil {
return nil, name, err
}
if err := customTagsRegistry.processField(fld, result); err != nil {
return nil, name, err
}
if !ignoreOas {
if err := result.processOasTag(fld); err != nil {
return nil, name, err
}
}
fKind := fld.Type.Kind()
objValidatorUsed := false
if result.Type == JsonObject {
if used, err := setPropertyValidatorObjectValidatorForStruct(fld, result, ignoreOas); err != nil {
return nil, name, err
} else {
objValidatorUsed = used
}
} else if result.Type == JsonArray && fKind == reflect.Slice {
if used, err := setPropertyValidatorObjectValidatorForSlice(fld, result, ignoreOas); err != nil {
return nil, name, err
} else {
objValidatorUsed = used
}
}
if !objValidatorUsed {
result.ObjectValidator = nil
}
return result, name, nil
}
func setPropertyValidatorObjectValidatorForStruct(fld reflect.StructField, pv *PropertyValidator, ignoreOas bool) (used bool, err error) {
used = false
fKind := fld.Type.Kind()
if fKind == reflect.Struct {
if ptys, err := buildPropertyValidators(fld.Type, ignoreOas); err != nil {
return false, err
} else if len(ptys) > 0 && pv.ObjectValidator != nil {
pv.ObjectValidator.DisallowObject = false
pv.ObjectValidator.AllowArray = false
pv.ObjectValidator.Properties = ptys
used = true
}
} else if fKind == reflect.Ptr && fld.Type.Elem().Kind() == reflect.Struct {
if ptys, err := buildPropertyValidators(fld.Type.Elem(), ignoreOas); err != nil {
return false, err
} else if len(ptys) > 0 && pv.ObjectValidator != nil {
pv.ObjectValidator.DisallowObject = false
pv.ObjectValidator.AllowArray = false
pv.ObjectValidator.Properties = ptys
used = true
}
}
return
}
func setPropertyValidatorObjectValidatorForSlice(fld reflect.StructField, pv *PropertyValidator, ignoreOas bool) (used bool, err error) {
used = false
if fld.Type.Elem().Kind() == reflect.Struct {
if ptys, err := buildPropertyValidators(fld.Type.Elem(), ignoreOas); err != nil {
return false, err
} else if len(ptys) > 0 && pv.ObjectValidator != nil {
pv.ObjectValidator.DisallowObject = true
pv.ObjectValidator.AllowArray = true
pv.ObjectValidator.Properties = ptys
used = true
}
} else if fld.Type.Elem().Kind() == reflect.Ptr && fld.Type.Elem().Elem().Kind() == reflect.Struct {
if ptys, err := buildPropertyValidators(fld.Type.Elem().Elem(), ignoreOas); err != nil {
return false, err
} else if len(ptys) > 0 && pv.ObjectValidator != nil {
pv.ObjectValidator.DisallowObject = true
pv.ObjectValidator.AllowArray = true
pv.ObjectValidator.Properties = ptys
used = true
}
}
return
}
func initialPropertyValidator(fld reflect.StructField, name string) (*PropertyValidator, error) {
jsonFldType := detectFieldType(fld)
if tag, ok := fld.Tag.Lookup(tagNameV8nAs); ok {
asName := ternary(tag == "").string(name, tag)
result := propertiesRepo.getNamed(asName)
if result == nil {
return nil, fmt.Errorf(errMsgCannotFindPropertyInRepo, asName)
}
result = result.Clone()
// check types are compatible...
if result.Type != JsonAny && result.Type != jsonFldType {
return nil, fmt.Errorf(errMsgIncompatiblePropertyType, asName)
}
result.Type = jsonFldType
// make sure constraints and object validator are initialised...
if result.Constraints == nil {
result.Constraints = Constraints{}
}
if result.ObjectValidator == nil {
result.ObjectValidator = &Validator{
IgnoreUnknownProperties: false,
Properties: Properties{},
Constraints: Constraints{},
AllowArray: false,
DisallowObject: false,
}
}
return result, nil
}
return &PropertyValidator{
Type: jsonFldType,
NotNull: false,
Mandatory: false,
Constraints: Constraints{},
ObjectValidator: &Validator{
IgnoreUnknownProperties: false,
Properties: Properties{},
Constraints: Constraints{},
AllowArray: false,
DisallowObject: false,
},
}, nil
}
func getFieldName(fld reflect.StructField) string {
result := fld.Name
if rn, ok := getDefaultPropertyNameProvider().NameFor(fld); ok {
result = rn
}
return result
}
var timeType = reflect.TypeOf(time.Time{})
var valixTimeType = reflect.TypeOf(Time{})
func detectFieldType(fld reflect.StructField) (result JsonType) {
k := fld.Type.Kind()
isPtr := false
if k == reflect.Ptr {
isPtr = true
k = fld.Type.Elem().Kind()
}
result = JsonAny
switch k {
case reflect.String:
result = JsonString
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
result = JsonNumber
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
result = JsonNumber
case reflect.Float64, reflect.Float32:
result = JsonNumber
case reflect.Bool:
result = JsonBoolean
case reflect.Struct:
result = detectFieldTypeForStruct(isPtr, fld)
case reflect.Slice:
result = JsonArray
case reflect.Map:
result = detectFieldTypeForMap(fld)
}
return
}
func detectFieldTypeForStruct(isPtr bool, fld reflect.StructField) JsonType {
if (!isPtr && fld.Type.AssignableTo(timeType)) || (isPtr && fld.Type.Elem().AssignableTo(timeType)) ||
(!isPtr && fld.Type.AssignableTo(valixTimeType)) || (isPtr && fld.Type.Elem().AssignableTo(valixTimeType)) {
return JsonDatetime
}
return JsonObject
}
func detectFieldTypeForMap(fld reflect.StructField) JsonType {
if fld.Type.Key().Kind() == reflect.String && fld.Type.Elem().Kind() == reflect.Interface {
// only if it's a 'map[string]interface{}` (because that's a representation of a JSON object)...
// .Type.Key().Kind() --^ ^-- .Type.Elem().Kind()
return JsonObject
}
return JsonAny
}