github.com/wfusion/gofusion@v1.1.14/common/utils/gomonkey/dsl/patch_builder.go (about) 1 package dsl 2 3 import ( 4 "fmt" 5 "reflect" 6 ) 7 8 type FuncPara struct { 9 target interface{} 10 constraints []Constraint 11 behaviors []Behavior 12 } 13 14 type PatchBuilder struct { 15 patches *Patches 16 funcPara FuncPara 17 } 18 19 func NewPatchBuilder(patches *Patches) *PatchBuilder { 20 funcPara := FuncPara{target: nil, constraints: make([]Constraint, 0), 21 behaviors: make([]Behavior, 0)} 22 return &PatchBuilder{patches: patches, funcPara: funcPara} 23 } 24 25 func (this *PatchBuilder) Func(target interface{}) *PatchBuilder { 26 this.funcPara.target = target 27 return this 28 } 29 30 func (this *PatchBuilder) Stubs() *PatchBuilder { 31 return this 32 } 33 34 func (this *PatchBuilder) With(matcher ...Constraint) *PatchBuilder { 35 this.funcPara.constraints = append(this.funcPara.constraints, matcher...) 36 return this 37 } 38 39 func (this *PatchBuilder) Will(behavior Behavior) *PatchBuilder { 40 this.funcPara.behaviors = append(this.funcPara.behaviors, behavior) 41 return this 42 } 43 44 func (this *PatchBuilder) Then(behavior Behavior) *PatchBuilder { 45 this.funcPara.behaviors = append(this.funcPara.behaviors, behavior) 46 return this 47 } 48 49 func (this *PatchBuilder) End() { 50 funcType := reflect.TypeOf(this.funcPara.target) 51 t := reflect.ValueOf(this.funcPara.target) 52 d := reflect.MakeFunc(funcType, func(inputs []reflect.Value) []reflect.Value { 53 matchers := this.funcPara.constraints 54 for i, input := range inputs { 55 if !matchers[i].Eval(input.Interface()) { 56 info := fmt.Sprintf("input paras %v is not matched", input.Interface()) 57 panic(info) 58 } 59 } 60 return GetResultValues(funcType, this.funcPara.behaviors[0].Apply()[0]...) 61 }) 62 this.patches.ApplyCore(t, d) 63 }