di-go/registry/definition.go

132 lines
2.3 KiB
Go
Raw Normal View History

2018-04-03 09:02:31 +00:00
package registry
import (
"fmt"
"reflect"
cda "git.loafle.net/commons/di-go/annotation"
cur "git.loafle.net/commons/util-go/reflect"
)
type TypeDefinition struct {
FullName string
PkgName string
TypeName string
Type reflect.Type
RealType reflect.Type
2018-04-06 17:27:13 +00:00
TypeAnnotations map[string]cda.Annotation
2018-04-06 18:00:06 +00:00
MethodAnnotations map[string]map[string]cda.Annotation
2018-04-06 17:27:13 +00:00
Fields []*FieldDefinition
2018-04-03 09:02:31 +00:00
}
func (td *TypeDefinition) GetAnnotation(name string) cda.Annotation {
if nil == td.TypeAnnotations {
return nil
}
return td.TypeAnnotations[name]
}
2018-04-10 12:08:21 +00:00
func (td *TypeDefinition) GetTypeAnnotationByType(at reflect.Type, includeEmbedding bool) cda.Annotation {
2018-04-03 09:02:31 +00:00
if nil == td.TypeAnnotations {
return nil
}
for _, v := range td.TypeAnnotations {
if at == reflect.TypeOf(v) {
return v
}
if includeEmbedding {
if checkAnnotation(reflect.TypeOf(v), at) {
return v
}
}
}
return nil
}
2018-04-06 18:00:06 +00:00
func (td *TypeDefinition) GetMethodAnnotationByType(at reflect.Type, methodName string) cda.Annotation {
if nil == td.MethodAnnotations {
return nil
}
ms, ok := td.MethodAnnotations[methodName]
if !ok {
return nil
}
for _, v := range ms {
if at == reflect.TypeOf(v) {
return v
}
}
return nil
}
2018-04-03 09:02:31 +00:00
func checkAnnotation(t reflect.Type, st reflect.Type) bool {
rt, _, _ := cur.GetTypeInfo(t)
if reflect.Struct != rt.Kind() {
return false
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.Anonymous {
if f.Type == st {
return true
}
if checkAnnotation(f.Type, st) {
return true
}
}
}
return false
}
type FieldDefinition struct {
FieldName string
PkgName string
TypeName string
Type reflect.Type
RealType reflect.Type
Annotations map[string]cda.Annotation
}
func (fd *FieldDefinition) GetAnnotation(name string) cda.Annotation {
if nil == fd.Annotations {
return nil
}
return fd.Annotations[name]
}
func (fd *FieldDefinition) GetAnnotationByType(at reflect.Type, includeEmbedding bool) cda.Annotation {
if nil == fd.Annotations {
return nil
}
for _, v := range fd.Annotations {
if at == reflect.TypeOf(v) {
return v
}
if includeEmbedding {
if checkAnnotation(reflect.TypeOf(v), at) {
return v
}
}
}
return nil
}
func FullName(pkgName, typeName string) string {
return fmt.Sprintf("%s/%s", pkgName, typeName)
}