-
Notifications
You must be signed in to change notification settings - Fork 11
/
filtration.go
356 lines (298 loc) · 7.05 KB
/
filtration.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package filter
import (
"encoding/json"
"fmt"
"strings"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/strutil"
)
// Filtration definition. Sanitization Sanitizing Sanitize
type Filtration struct {
err error
// raw data
data map[string]any
// mark has apply filters
filtered bool
// filtered and clean data
cleanData map[string]any
// filter rules
filterRules []*Rule
}
// New a Filtration
func New(data map[string]any) *Filtration {
return &Filtration{
data: data,
// init map
cleanData: make(map[string]any),
}
}
// LoadData set raw data for filtering.
func (f *Filtration) LoadData(data map[string]any) {
f.data = data
}
// ResetData reset raw and filtered data
func (f *Filtration) ResetData(resetRaw bool) {
f.err = nil
f.filtered = false
// reset data.
if resetRaw {
f.data = make(map[string]any)
}
f.cleanData = make(map[string]any)
}
// ResetRules reset rules and filtered data
func (f *Filtration) ResetRules() {
f.err = nil
f.filtered = false
// clear rules
f.filterRules = f.filterRules[:0]
// clear cleanData
f.cleanData = make(map[string]any)
}
// Clear all data and rules
func (f *Filtration) Clear() {
f.data = make(map[string]any)
f.ResetRules()
}
/*************************************************************
* add rules and filtering data
*************************************************************/
// AddRule add filter(s) rule.
//
// Usage:
//
// f.AddRule("name", "trim")
// f.AddRule("age", "int")
// f.AddRule("age", "trim|int")
func (f *Filtration) AddRule(field string, rule any) *Rule {
fields := strutil.Split(field, ",")
if len(fields) == 0 {
panic("filter: invalid fields parameters, cannot be empty")
}
r := newRule(fields)
if strRule, ok := rule.(string); ok {
strRule = strings.TrimSpace(strRule)
rules := strutil.Split(strings.Trim(strRule, "|:"), "|")
if len(rules) == 0 {
panic("filter: invalid 'rule' params, cannot be empty")
}
r.AddFilters(rules...)
} else if fn, ok := rule.(func(any) (any, error)); ok {
r.SetFilterFunc(fn)
} else {
panic("filter: 'rule' params cannot be empty and type allow: string, func")
}
f.filterRules = append(f.filterRules, r)
return r
}
// AddRules add multi rules.
//
// Usage:
//
// f.AddRules(map[string]string{
// "name": "trim|lower",
// "age": "trim|int",
// })
func (f *Filtration) AddRules(rules map[string]string) *Filtration {
for field, rule := range rules {
f.AddRule(field, rule)
}
return f
}
// Sanitize is alias of the Filtering()
func (f *Filtration) Sanitize() error {
return f.Filtering()
}
// Filtering apply all filter rules, filtering data
func (f *Filtration) Filtering() error {
if f.filtered || f.err != nil {
return f.err
}
// apply rule to validate data.
for _, rule := range f.filterRules {
if err := rule.Apply(f); err != nil { // has error
f.err = err
break
}
}
f.filtered = true
return f.err
}
// IsOK of to apply filters
func (f *Filtration) IsOK() bool {
return f.err == nil
}
// Err get error
func (f *Filtration) Err() error {
return f.err
}
/*************************************************************
* get raw/filtered data value
*************************************************************/
// Raw get raw value by key
func (f *Filtration) Raw(key string) (any, bool) {
return maputil.GetByPath(key, f.data)
}
// Safe get filtered value by key
func (f *Filtration) Safe(key string) (any, bool) {
return maputil.GetByPath(key, f.cleanData)
}
// SafeVal get filtered value by key
func (f *Filtration) SafeVal(key string) any {
val, _ := maputil.GetByPath(key, f.cleanData)
return val
}
// Get value by key
func (f *Filtration) Get(key string) (any, bool) {
val, ok := maputil.GetByPath(key, f.cleanData)
if !ok {
val, ok = maputil.GetByPath(key, f.data)
}
return val, ok
}
// MustGet value by key
func (f *Filtration) MustGet(key string) any {
val, _ := f.Get(key)
return val
}
// Int get a int value from filtered data.
func (f *Filtration) Int(key string) int {
if val, ok := f.Safe(key); ok {
return MustInt(val)
}
return 0
}
// Int64 get a int value from filtered data.
func (f *Filtration) Int64(key string) int64 {
if val, ok := f.Safe(key); ok {
return MustInt64(val)
}
return 0
}
// Bool value get from the filtered data.
func (f *Filtration) Bool(key string) bool {
if val, ok := f.Safe(key); ok {
return val.(bool)
}
return false
}
// String get a string value from filtered data.
func (f *Filtration) String(key string) string {
val, ok := f.Safe(key)
if !ok {
return ""
}
// is string.
if str, ok := val.(string); ok {
return str
}
return fmt.Sprint(val)
}
// BindStruct bind the filtered data to struct.
func (f *Filtration) BindStruct(ptr any) error {
bts, err := json.Marshal(f.cleanData)
if err != nil {
return err
}
return json.Unmarshal(bts, ptr)
}
// RawData get raw data
func (f *Filtration) RawData() map[string]any {
return f.data
}
// CleanData get filtered data
func (f *Filtration) CleanData() map[string]any {
return f.cleanData
}
/*************************************************************
* filtering rule
*************************************************************/
// Rule definition
type Rule struct {
// fields to filter
fields []string
// filter name list
filters []string
// filter args. { index: "args" }
filterArgs map[int]string
// user custom filter func
filterFunc func(val any) (any, error)
// default value for the rule
defaultVal any
}
func newRule(fields []string) *Rule {
return &Rule{
fields: fields,
// init map
filterArgs: make(map[int]string),
}
}
// SetDefaultVal set default value for the rule
func (r *Rule) SetDefaultVal(defaultVal any) *Rule {
r.defaultVal = defaultVal
return r
}
// SetFilterFunc user custom filter func
func (r *Rule) SetFilterFunc(fn func(val any) (any, error)) *Rule {
r.filterFunc = fn
return r
}
// AddFilters add multi filter(s).
//
// Usage:
//
// r.AddFilters("int", "str2arr:,")
func (r *Rule) AddFilters(filters ...string) *Rule {
for _, filterName := range filters {
pos := strings.IndexRune(filterName, ':')
if pos > 0 { // has filter args
name := filterName[:pos]
index := len(r.filters)
r.filters = append(r.filters, name)
r.filterArgs[index] = filterName[pos+1:]
} else {
r.filters = append(r.filters, filterName)
}
}
return r
}
// Apply rule for the rule fields
func (r *Rule) Apply(f *Filtration) (err error) {
// validate field
for _, field := range r.Fields() {
// get field value.
val, has := f.Get(field)
if !has { // no field
if r.defaultVal == nil {
continue
}
// has default value
val = r.defaultVal
}
// custom filter func
if r.filterFunc != nil {
val, err = r.filterFunc(val)
if err != nil {
return err
}
// save filtered value.
f.cleanData[field] = val
continue
}
// call built-in filters
for i, name := range r.filters {
args := parseArgString(r.filterArgs[i])
val, err = Apply(name, val, args)
if err != nil {
return err
}
}
// save filtered value.
f.cleanData[field] = val
}
return
}
// Fields name get
func (r *Rule) Fields() []string {
return r.fields
}