/
decorator.go
68 lines (46 loc) · 1.68 KB
/
decorator.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
// Copyright 2016-2018 Granitic. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.
package rdbms
import (
"github.com/graniticio/granitic/ioc"
"github.com/graniticio/granitic/logging"
"github.com/graniticio/granitic/rdbms"
"github.com/graniticio/granitic/reflecttools"
"reflect"
)
type clientManagerDecorator struct {
fieldNameManager map[string]rdbms.RdbmsClientManager
log logging.Logger
}
func (cmd *clientManagerDecorator) OfInterest(component *ioc.Component) bool {
result := false
for field, manager := range cmd.fieldNameManager {
i := component.Instance
if fieldPresent := reflecttools.HasFieldOfName(i, field); !fieldPresent {
continue
}
targetFieldType := reflecttools.TypeOfField(i, field)
managerType := reflect.TypeOf(manager)
v := reflect.ValueOf(i).Elem().FieldByName(field)
if managerType.AssignableTo(targetFieldType) && v.IsNil() {
cmd.log.LogTracef("%s.%s needs a client manager", component.Name, field)
return true
}
}
return result
}
func (cmd *clientManagerDecorator) DecorateComponent(component *ioc.Component, container *ioc.ComponentContainer) {
for field, manager := range cmd.fieldNameManager {
i := component.Instance
if fieldPresent := reflecttools.HasFieldOfName(i, field); !fieldPresent {
continue
}
targetFieldType := reflecttools.TypeOfField(i, field)
managerType := reflect.TypeOf(manager)
v := reflect.ValueOf(i).Elem().FieldByName(field)
if managerType.AssignableTo(targetFieldType) && v.IsNil() {
rc := reflect.ValueOf(i).Elem()
rc.FieldByName(field).Set(reflect.ValueOf(manager))
}
}
}