-
Notifications
You must be signed in to change notification settings - Fork 19
/
choice_def.go
69 lines (57 loc) · 2.02 KB
/
choice_def.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
package statemachine
import (
"reflect"
"github.com/Gurpartap/statemachine-go/internal/dynafunc"
)
type ChoiceConditionDef struct {
Label string `json:",omitempty" hcl:"label" hcle:"omitempty"`
RegisteredFunc string `json:",omitempty" hcl:"registered_func" hcle:"omitempty"`
Condition ChoiceCondition `json:"-" hcle:"omit"`
}
type ChoiceDef struct {
Condition *ChoiceConditionDef `json:",omitempty" hcl:"condition" hcle:"omitempty"`
UnlessGuard *TransitionGuardDef `json:",omitempty" hcl:"unless_condition" hcle:"omitempty"`
OnTrue *EventDef `json:",omitempty" hcl:"on_true" hcle:"omitempty"`
OnFalse *EventDef `json:",omitempty" hcl:"on_false" hcle:"omitempty"`
}
func (def *ChoiceDef) SetLabel(label string) {
def.Condition.Label = label
}
func (def *ChoiceDef) SetCondition(condition ChoiceCondition) {
def.Condition = &ChoiceConditionDef{Condition: condition}
}
func (def *ChoiceDef) SetUnlessGuard(guard TransitionGuard) {
def.UnlessGuard = &TransitionGuardDef{Guard: guard}
}
func (def *ChoiceDef) SetOnTrue(eventBuilderFn func(eventBuilder EventBuilder)) {
eventBuilder := NewEventBuilder("")
eventBuilderFn(eventBuilder)
e := newEventImpl()
eventBuilder.Build(e)
def.OnTrue = e.def
}
func (def *ChoiceDef) SetOnFalse(eventBuilderFn func(eventBuilder EventBuilder)) {
eventBuilder := NewEventBuilder("")
eventBuilderFn(eventBuilder)
e := newEventImpl()
eventBuilder.Build(e)
def.OnFalse = e.def
}
func execChoice(condition ChoiceCondition, args map[reflect.Type]interface{}) bool {
switch reflect.TypeOf(condition).Kind() {
case reflect.Func:
fn := dynafunc.NewDynamicFunc(condition, args)
if err := fn.Call(); err != nil {
panic(err)
}
// condition func must return a bool
return fn.Out[0].Bool()
case reflect.Ptr:
if reflect.ValueOf(condition).Elem().Kind() == reflect.Bool {
return reflect.ValueOf(condition).Elem().Bool()
}
fallthrough
default:
panic("choice must either be a compatible func or pointer to a bool variable")
}
}