-
Notifications
You must be signed in to change notification settings - Fork 54
/
builders.go
105 lines (100 loc) · 2.41 KB
/
builders.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
package expression
import (
"reflect"
"strings"
)
func makeContainsExpr(e1, e2 func(Context) interface{}) func(Context) interface{} { // nolint: gocyclo
return func(ctx Context) interface{} {
search, ok := e2((ctx)).(string)
if !ok {
return false
}
switch container := e1((ctx)).(type) {
case string:
return strings.Contains(container, search)
case []string:
for _, s := range container {
if s == search {
return true
}
}
case []interface{}:
for _, k := range container {
if s, ok := k.(string); ok && s == search {
return true
}
}
default:
return false
}
return false
}
}
func makeFilter(fn valueFn, name string, args []valueFn) valueFn {
return func(ctx Context) interface{} {
return ctx.ApplyFilter(name, fn, args)
}
}
func makeIndexExpr(obj, index func(Context) interface{}) func(Context) interface{} { // nolint: gocyclo
return func(ctx Context) interface{} {
ref := reflect.ValueOf(obj(ctx))
i := reflect.ValueOf(index(ctx))
if !ref.IsValid() || !i.IsValid() {
return nil
}
switch ref.Kind() {
case reflect.Array, reflect.Slice:
switch i.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := int(i.Int())
if n < 0 {
n = ref.Len() + n
}
if 0 <= n && n < ref.Len() {
return ToLiquid(ref.Index(n).Interface())
}
}
case reflect.Map:
if i.Type().ConvertibleTo(ref.Type().Key()) {
item := ref.MapIndex(i.Convert(ref.Type().Key()))
if item.IsValid() {
return ToLiquid(item.Interface())
}
}
}
return nil
}
}
func makeObjectPropertyExpr(obj func(Context) interface{}, attr string) func(Context) interface{} { // nolint: gocyclo
const sizeString = "size"
return func(ctx Context) interface{} {
ref := reflect.ValueOf(obj(ctx))
switch ref.Kind() {
case reflect.Array, reflect.Slice:
if ref.Len() == 0 {
return nil
}
switch attr {
case "first":
return ToLiquid(ref.Index(0).Interface())
case "last":
return ToLiquid(ref.Index(ref.Len() - 1).Interface())
case sizeString:
return ToLiquid(ref.Len())
}
case reflect.String:
if attr == sizeString {
return ToLiquid(ref.Len())
}
case reflect.Map:
value := ref.MapIndex(reflect.ValueOf(attr))
if value.Kind() != reflect.Invalid {
return ToLiquid(value.Interface())
}
if attr == sizeString {
return reflect.ValueOf(attr).Len()
}
}
return nil
}
}