-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontext.go
More file actions
569 lines (512 loc) · 16.7 KB
/
context.go
File metadata and controls
569 lines (512 loc) · 16.7 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package valix
import (
"fmt"
"golang.org/x/text/language"
"net/http"
"strings"
)
// ValidatorContext is the context that is generated by the Validator and passed to
// each descendant Validator, PropertyValidator and each Constraint.Check function
type ValidatorContext struct {
// ok is the final result of the validator
ok bool
// stopOnFirst is whether the validator has been set to stop on first violation
stopOnFirst bool
// continueAll is whether entire validation is ok to continue
continueAll bool
// root is the original starting object (map or slice) for the validator
root interface{}
// rootValidator is the starting validator
rootValidator *Validator
// violations is the collected violations
violations []*Violation
// pathStack is the path as each property or array index is checked
pathStack []*pathStackItem
// i18nContext is the actual I18nContext used to perform translations
i18nContext I18nContext
// locking is the locking level of the context
locking uint
}
type Conditions []string
func newValidatorContext(root interface{}, rootValidator *Validator, stopOnFirst bool, i18nCtx I18nContext) *ValidatorContext {
return &ValidatorContext{
ok: true,
stopOnFirst: stopOnFirst,
continueAll: true,
root: root,
rootValidator: rootValidator,
violations: []*Violation{},
pathStack: []*pathStackItem{newRootPathStackItem(root, rootValidator)},
i18nContext: obtainI18nContext(i18nCtx),
}
}
func newEmptyValidatorContext(i18nCtx I18nContext) *ValidatorContext {
return &ValidatorContext{
ok: true,
stopOnFirst: false,
continueAll: true,
root: nil,
rootValidator: nil,
violations: []*Violation{},
pathStack: []*pathStackItem{newRootPathStackItem(nil, nil)},
i18nContext: obtainI18nContext(i18nCtx),
}
}
// AddViolation adds a Violation to the validation context
//
// Note: Adding a violation always causes the validator to fail!
func (vc *ValidatorContext) AddViolation(v *Violation) {
if vc.locking == 0 {
vc.violations = append(vc.violations, v)
vc.ok = false
if vc.stopOnFirst {
vc.continueAll = false
}
}
}
// AddViolationForCurrent adds a Violation to the validation context for
// the current property and path
//
// Note 1: Use the `translate` arg to determine if the message is to be i18n translated
//
// Note 2: Adding a violation always causes the validator to fail!
func (vc *ValidatorContext) AddViolationForCurrent(msg string, translate bool, codes ...interface{}) {
if vc.locking == 0 {
curr := vc.currentStackItem()
useMsg := msg
if translate {
useMsg = vc.TranslateMessage(msg)
}
vc.AddViolation(NewViolation(curr.propertyAsString(), curr.path, useMsg, codes...))
}
}
// internal and message is already translated
func (vc *ValidatorContext) addTranslatedViolationForCurrent(msg string, codes ...interface{}) {
if vc.locking == 0 {
curr := vc.currentStackItem()
vc.AddViolation(NewViolation(curr.propertyAsString(), curr.path, msg, codes...))
}
}
// internal and message gets translated
func (vc *ValidatorContext) addUnTranslatedViolationForCurrent(msg string, codes ...interface{}) {
if vc.locking == 0 {
vc.addTranslatedViolationForCurrent(vc.TranslateMessage(msg), codes...)
}
}
// internal and message is translated
func (vc *ValidatorContext) addViolationPropertyForCurrent(name string, msg string, codes ...interface{}) {
if vc.locking == 0 {
curr := vc.currentStackItem()
vc.AddViolation(NewViolation(name, curr.asPath(), vc.TranslateMessage(msg), codes...))
}
}
// Stop causes the entire validation to stop - i.e. not further constraints or
// property value validations are performed
//
// Note: This does not affect whether the validator succeeds or fails
func (vc *ValidatorContext) Stop() {
if vc.locking == 0 {
vc.continueAll = false
}
}
// CeaseFurther causes further constraints and property validators on the current
// property to be ceased (i.e. not performed)
//
// Note: This does not affect whether the validator succeeds or fails
func (vc *ValidatorContext) CeaseFurther() {
if vc.locking == 0 {
vc.currentStackItem().stopped = true
}
}
// CeaseFurtherIf causes further constraints and property validators on the current
// property to be ceased if the condition is true
//
// Note: This does not affect whether the validator succeeds or fails
func (vc *ValidatorContext) CeaseFurtherIf(condition bool) {
if vc.locking == 0 {
vc.currentStackItem().stopped = condition
}
}
func (vc *ValidatorContext) Lock() {
vc.locking++
}
func (vc *ValidatorContext) UnLock() {
if vc.locking > 0 {
vc.locking--
}
}
// CurrentProperty returns the current property - which may be a string (for property name)
// or an int (for array index)
//
// Alternatively, to obtain the current property name use...
// CurrentPropertyName
// or the current array index use...
// CurrentArrayIndex
func (vc *ValidatorContext) CurrentProperty() interface{} {
return vc.currentStackItem().property
}
// CurrentPropertyName returns the current property name (or nil if current is an array index)
func (vc *ValidatorContext) CurrentPropertyName() *string {
pty := vc.CurrentProperty()
if s, ok := pty.(string); ok {
return &s
}
return nil
}
// CurrentArrayIndex returns the current array index (or nil if current is a property name)
func (vc *ValidatorContext) CurrentArrayIndex() *int {
pty := vc.CurrentProperty()
if i, ok := pty.(int); ok {
return &i
}
return nil
}
func (vc *ValidatorContext) currentStackItem() *pathStackItem {
return vc.pathStack[len(vc.pathStack)-1]
}
// CurrentPath returns the current property path
func (vc *ValidatorContext) CurrentPath() string {
return vc.currentStackItem().path
}
// CurrentValue returns the current property value
func (vc *ValidatorContext) CurrentValue() interface{} {
return vc.currentStackItem().value
}
// CurrentDepth returns the current depth of the context - i.e. how many properties deep in the tree
func (vc *ValidatorContext) CurrentDepth() int {
return len(vc.pathStack) - 1
}
func (vc *ValidatorContext) AncestryIndex(level uint) (index int, max int, ok bool) {
atLevel := uint(0)
for i := len(vc.pathStack) - 1; i >= 0; i-- {
pi := vc.pathStack[i]
if idx, ok := pi.property.(int); ok {
if atLevel == level {
// the next upwards must be an array (or should be!) - so get its length
if i > 0 {
pip := vc.pathStack[i-1]
if sl, ok := pip.value.([]interface{}); ok {
return idx, len(sl) - 1, true
}
}
return idx, -1, true
} else {
atLevel++
}
}
}
return 0, -1, false
}
// AncestorProperty returns an ancestor property - which may be a string (for property name)
// or an int (for array index)
//
// Alternatively, to obtain an ancestor property name use...
// AncestorPropertyName
// or an ancestor array index use...
// AncestorArrayIndex
func (vc *ValidatorContext) AncestorProperty(level uint) (interface{}, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
return itm.property, true
}
return nil, false
}
// AncestorPropertyName returns an ancestor property name (or nil if ancestor property is an array index)
func (vc *ValidatorContext) AncestorPropertyName(level uint) (*string, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
if s, oks := itm.property.(string); oks {
return &s, true
}
}
return nil, false
}
// AncestorArrayIndex returns an ancestor array index (or nil if ancestor is a property name)
func (vc *ValidatorContext) AncestorArrayIndex(level uint) (*int, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
if i, oki := itm.property.(int); oki {
return &i, true
}
}
return nil, false
}
// AncestorPath returns an ancestor property path
//
// The level determines how far up the ancestry - 0 is parent, 1 is grandparent, etc.
func (vc *ValidatorContext) AncestorPath(level uint) (*string, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
path := itm.path
return &path, true
}
return nil, false
}
// AncestorValue returns an ancestor value
func (vc *ValidatorContext) AncestorValue(level uint) (interface{}, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
return itm.value, true
}
return nil, false
}
// ancestorValueObject returns an ancestor value (but only if it is an object - i.e. map[string]interface{})
// also returns the adjusted ancestry
func (vc *ValidatorContext) ancestorValueObject(level uint) (map[string]interface{}, []interface{}, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
if obj, ok := itm.value.(map[string]interface{}); ok {
ancestry := vc.ValuesAncestry()
if len(ancestry) > 1 {
ancestry = ancestry[2:]
}
return obj, ancestry, true
}
}
return nil, nil, false
}
// ancestorValueAndIndex returns an ancestor value
func (vc *ValidatorContext) ancestorValueAndIndex(level uint) (interface{}, int, bool) {
if itm, ok := vc.ancestorStackItem(level); ok {
if sl, ok := itm.value.([]interface{}); ok {
// if the value is a slice(array) - then also figure out current index in that array...
if idxItm, ok := vc.ancestorStackItem(level - 1); ok {
if idx, ok := idxItm.property.(int); ok {
return sl, idx, true
}
}
}
return itm.value, -1, true
}
return nil, -1, false
}
// ValuesAncestry returns the values ancestry (where the first item is parent, second is grandparent etc.)
func (vc *ValidatorContext) ValuesAncestry() []interface{} {
l := len(vc.pathStack)
result := make([]interface{}, l)
for i, sti := range vc.pathStack {
result[l-1-i] = sti.value
}
return result
}
// SetCondition sets a specified condition (token)
//
// Note: if the condition (token) is prefixed with '!' then this is the same as calling ClearCondition
func (vc *ValidatorContext) SetCondition(condition string) {
if strings.HasPrefix(condition, "!") {
vc.ClearCondition(condition[1:])
return
}
vc.currentStackItem().conditions[condition] = true
}
// SetParentCondition sets a specified condition (token) on the parent in the object tree
//
// Note: if the condition (token) is prefixed with '!' then this is the same as calling ClearParentCondition
func (vc *ValidatorContext) SetParentCondition(condition string) {
if strings.HasPrefix(condition, "!") {
vc.ClearParentCondition(condition[1:])
return
}
if len(vc.pathStack) > 1 {
vc.pathStack[len(vc.pathStack)-2].conditions[condition] = true
}
vc.currentStackItem().conditions[condition] = true
}
// SetGlobalCondition sets a specified condition (token) for the entire validator context
//
// Note: if the condition (token) is prefixed with '!' then this is the same as calling ClearGlobalCondition
func (vc *ValidatorContext) SetGlobalCondition(condition string) {
if strings.HasPrefix(condition, "!") {
vc.ClearGlobalCondition(condition[1:])
return
}
for _, ps := range vc.pathStack {
ps.conditions[condition] = true
}
}
// ClearCondition clears a specified condition (token)
func (vc *ValidatorContext) ClearCondition(condition string) {
delete(vc.currentStackItem().conditions, condition)
}
// ClearParentCondition clears a specified condition (token) on the parent in the object tree
func (vc *ValidatorContext) ClearParentCondition(condition string) {
if len(vc.pathStack) > 1 {
delete(vc.pathStack[len(vc.pathStack)-2].conditions, condition)
}
delete(vc.currentStackItem().conditions, condition)
}
// ClearGlobalCondition clears a specified condition (token) on the parent in the object tree
func (vc *ValidatorContext) ClearGlobalCondition(condition string) {
for _, ps := range vc.pathStack {
delete(ps.conditions, condition)
}
}
// IsCondition checks whether a specified condition (token) has been set
func (vc *ValidatorContext) IsCondition(condition string) bool {
return vc.currentStackItem().conditions[condition]
}
// meetsWhenConditions checks whether the supplied conditions are met
//
// If any of the condition tokens are prefixed with '!' and that condition token has been set then `false` is returned
// If any of the condition tokens, not prefixed with '!', have been set then `true` is returned
//
// Note: If any empty slice is passed as the conditions arg then `true` is returned (i.e. no conditions to be met)
func (vc *ValidatorContext) meetsWhenConditions(conditions Conditions) bool {
if len(conditions) == 0 {
return true
}
anyExcluded := false
anyMet := false
anyCount := 0
currentConditions := vc.currentStackItem().conditions
for _, condition := range conditions {
if strings.HasPrefix(condition, "!") {
if currentConditions[condition[1:]] {
anyExcluded = true
break
}
} else {
anyCount++
if currentConditions[condition] {
anyMet = true
}
}
}
return !anyExcluded && (anyMet || anyCount == 0)
}
func (vc *ValidatorContext) meetsUnwantedConditions(conditions Conditions) bool {
if len(conditions) == 0 {
return true
}
result := true
currentConditions := vc.currentStackItem().conditions
for _, condition := range conditions {
if strings.HasPrefix(condition, "!") {
result = currentConditions[condition[1:]]
if !result {
break
}
} else {
result = !currentConditions[condition]
if !result {
break
}
}
}
return result
}
func (vc *ValidatorContext) setConditionsFromRequest(req *http.Request) {
vc.SetCondition("METHOD_" + req.Method)
contentLang := DefaultLanguage
contentRegion := DefaultRegion
tags, _, err := language.ParseAcceptLanguage(req.Header.Get("Content-Language"))
if err == nil {
for _, tag := range tags {
baseLang, _ := tag.Base()
if baseLang.String() == defaultLanguage(baseLang.String()) {
contentLang = baseLang.String()
_, _, rawRgn := tag.Raw()
if rawRgn.String() != "ZZ" {
contentRegion = rawRgn.String()
}
break
}
}
}
vc.SetCondition("LANG_" + contentLang)
vc.SetCondition("RGN_" + contentRegion)
}
func (vc *ValidatorContext) setInitialConditions(conditions ...string) {
for _, c := range conditions {
vc.SetCondition(c)
}
}
func (vc *ValidatorContext) ancestorStackItem(level uint) (*pathStackItem, bool) {
// note: -2 because... it's -1 for len and -1 for up one
idx := len(vc.pathStack) - 2 - int(level)
if idx < 0 {
return nil, false
}
return vc.pathStack[idx], true
}
func (vc *ValidatorContext) pushPathProperty(property string, value interface{}, validator interface{}) {
vc.pathStack = append(vc.pathStack, vc.currentStackItem().clone(property, value, validator))
}
func (vc *ValidatorContext) pushPathIndex(idx int, value interface{}, validator interface{}) {
vc.pathStack = append(vc.pathStack, vc.currentStackItem().clone(idx, value, validator))
}
func (vc *ValidatorContext) popPath() {
if len(vc.pathStack) > 1 {
vc.pathStack = vc.pathStack[:len(vc.pathStack)-1]
}
}
func (vc *ValidatorContext) continuePty() bool {
return !vc.currentStackItem().stopped
}
// TranslateMessage implements I18nContext.TranslateMessage (and relays it to internal i18nContext)
func (vc *ValidatorContext) TranslateMessage(msg string) string {
return vc.i18nContext.TranslateMessage(msg)
}
// TranslateFormat implements I18nContext.TranslateFormat (and relays it to internal i18nContext)
func (vc *ValidatorContext) TranslateFormat(format string, a ...interface{}) string {
return vc.i18nContext.TranslateFormat(format, a...)
}
// TranslateToken implements I18nContext.TranslateToken (and relays it to internal i18nContext)
func (vc *ValidatorContext) TranslateToken(token string) string {
return vc.i18nContext.TranslateToken(token)
}
// Language implements I18nContext.Language (and relays it to internal i18nContext)
func (vc *ValidatorContext) Language() string {
return vc.i18nContext.Language()
}
// Region implements I18nContext.Region (and relays it to internal i18nContext)
func (vc *ValidatorContext) Region() string {
return vc.i18nContext.Region()
}
type pathStackItem struct {
property interface{}
path string
value interface{}
validator interface{}
stopped bool
conditions map[string]bool
}
func newRootPathStackItem(value interface{}, validator interface{}) *pathStackItem {
return &pathStackItem{
property: nil,
path: "",
value: value,
validator: validator,
stopped: false,
conditions: map[string]bool{},
}
}
func (p *pathStackItem) clone(pty interface{}, value interface{}, validator interface{}) *pathStackItem {
result := &pathStackItem{
property: pty,
path: p.asPath(),
value: value,
validator: validator,
conditions: make(map[string]bool, len(p.conditions)),
}
for k, v := range p.conditions {
result.conditions[k] = v
}
return result
}
func (p *pathStackItem) asPath() string {
if p.property == nil {
return ""
}
if pty, ok := p.property.(string); ok {
if p.path != "" {
return p.path + "." + pty
}
return pty
}
return p.path + p.propertyAsString()
}
func (p *pathStackItem) propertyAsString() string {
if p.property == nil {
return ""
}
if s, ok := p.property.(string); ok {
return s
}
i, _ := p.property.(int)
return fmt.Sprintf("[%d]", i)
}