-
Notifications
You must be signed in to change notification settings - Fork 1
/
statemachine.go
78 lines (63 loc) · 1.79 KB
/
statemachine.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
package statemachine
import "errors"
// StateMachine ...
type StateMachine struct {
State State
Transitions map[string]Transitions
Callbacks map[string][]Callback
Errors map[string]error
}
// New : returns a new statemachine
func New(state State) *StateMachine {
return &StateMachine{
State: state,
Transitions: make(map[string]Transitions),
Callbacks: make(map[string][]Callback),
Errors: make(map[string]error),
}
}
// When : sets the transition for a given event
func (s *StateMachine) When(event string, t Transitions) {
s.Transitions[event] = t
}
// On : sets a callback for a given state change
func (s *StateMachine) On(state string, c Callback) {
s.Callbacks[state] = append(s.Callbacks[state], c)
}
// Trigger : trigger a state change
func (s *StateMachine) Trigger(event string, t interface{}) error {
return s.change(event, t)
}
// Error : sets an error to return when there are no valid transitions for the current state
func (s *StateMachine) Error(state string, err error) {
s.Errors[state] = err
}
// ValidateTransition : returns an error if there are no transitions for an event
func (s *StateMachine) ValidateTransition(event, state string) error {
if s.Transitions[event] == nil {
return errors.New("invalid event: " + event)
}
if state == "" || s.Transitions[event][state] == "" {
err := s.Errors[state]
if err != nil {
return err
}
return errors.New("invalid state transition")
}
return nil
}
func (s *StateMachine) change(event string, t interface{}) error {
err := s.ValidateTransition(event, s.State.GetState())
if err != nil {
return err
}
state := s.Transitions[event][s.State.GetState()]
for _, cb := range s.Callbacks[state] {
err := cb(state, t)
if err != nil {
return err
}
}
s.State.SetState(state)
return nil
}