-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathvalidator.go
More file actions
105 lines (87 loc) · 2.19 KB
/
Copy pathvalidator.go
File metadata and controls
105 lines (87 loc) · 2.19 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
package jsonlogic
import (
"encoding/json"
"io"
)
// IsValid reads a JSON Logic rule from io.Reader and validates its syntax.
// It checks if the rule conforms to valid JSON Logic format and uses supported operators.
//
// Parameters:
// - rule: io.Reader containing the JSON Logic rule to validate
//
// Returns:
// - bool: true if the rule is valid, false otherwise
//
// The function returns false if the JSON cannot be parsed or if the rule contains invalid operators.
func IsValid(rule io.Reader) bool {
var _rule any
decoderRule := json.NewDecoder(rule)
err := decoderRule.Decode(&_rule)
if err != nil {
return false
}
return ValidateJsonLogic(_rule)
}
// ValidateJsonLogic validates if the given rules conform to JSON Logic format.
// It recursively checks the structure and ensures all operators are supported.
//
// Parameters:
// - rules: any value representing the JSON Logic rule to validate
//
// Returns:
// - bool: true if the rules are valid JSON Logic, false otherwise
//
// The function handles primitives, maps (operators), slices (arrays), and variable references.
func ValidateJsonLogic(rules any) bool {
if isVar(rules) {
return true
}
if rulesMap, ok := rules.(map[string]any); ok {
// A map with more than 1 key counts as a primitive so it's time to end recursion
if len(rulesMap) > 1 {
return true
}
for operator, value := range rulesMap {
if !isOperator(operator) {
return false
}
return ValidateJsonLogic(value)
}
}
if rulesSlice, ok := rules.([]any); ok {
for _, value := range rulesSlice {
_, isSlice := value.([]any)
_, isMap := value.(map[string]any)
if isSlice || isMap {
if ValidateJsonLogic(value) {
continue
}
return false
}
if isVar(value) || isPrimitive(value) {
continue
}
}
return true
}
return isPrimitive(rules)
}
func isOperator(op string) bool {
operatorsLock.RLock()
_, isOperator := operators[op]
operatorsLock.RUnlock()
return isOperator
}
func isVar(value any) bool {
m, ok := value.(map[string]any)
if !ok {
return false
}
_var, ok := m["var"]
if !ok {
return false
}
_, isStr := _var.(string)
_, isNum := _var.(float64)
return isStr || isNum || _var == nil
}