-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule_builder.go
77 lines (63 loc) · 1.93 KB
/
rule_builder.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
package golymorph
import (
"github.com/SoulKa/golymorph/objectpath"
"reflect"
)
type ruleBuilder struct {
errors []error
valuePath objectpath.ObjectPath
comparatorFunc func(any) bool
newType reflect.Type
}
type ruleBuilderBase interface {
// WhenValueAt sets the path to the value in the source to compare.
WhenValueAt(valuePath string) ruleBuilderConditionSetter
}
type ruleBuilderConditionSetter interface {
// IsEqualTo sets the value to compare to.
IsEqualTo(value any) ruleBuilderTypeAssigner
// Matches sets the function to use to compare the value at ValuePath to.
Matches(comparator func(any) bool) ruleBuilderTypeAssigner
}
type ruleBuilderTypeAssigner interface {
// ThenAssignType sets the type to assign to the target if the rule matches.
ThenAssignType(newType reflect.Type) ruleBuilderFinalizer
}
type ruleBuilderFinalizer interface {
// Build builds the Rule and returns the errors encountered while building.
Build() ([]error, Rule)
}
// NewRuleBuilder creates a new ruleBuilder. It enables a fluent interface for building a Rule.
func NewRuleBuilder() ruleBuilderBase {
return &ruleBuilder{}
}
func (b *ruleBuilder) WhenValueAt(valuePath string) ruleBuilderConditionSetter {
if err, path := objectpath.NewObjectPathFromString(valuePath); err != nil {
b.appendError(err)
} else {
b.valuePath = *path
}
return b
}
func (b *ruleBuilder) IsEqualTo(value any) ruleBuilderTypeAssigner {
b.comparatorFunc = func(v any) bool { return v == value }
return b
}
func (b *ruleBuilder) Matches(comparator func(any) bool) ruleBuilderTypeAssigner {
b.comparatorFunc = comparator
return b
}
func (b *ruleBuilder) ThenAssignType(newType reflect.Type) ruleBuilderFinalizer {
b.newType = newType
return b
}
func (b *ruleBuilder) Build() ([]error, Rule) {
return b.errors, Rule{
b.valuePath,
b.comparatorFunc,
b.newType,
}
}
func (b *ruleBuilder) appendError(err error) {
b.errors = append(b.errors, err)
}