di/registry/definition.go

112 lines
1.9 KiB
Go
Raw Permalink Normal View History

2017-12-03 13:54:09 +00:00
package registry
2017-12-05 13:28:42 +00:00
import (
2017-12-06 00:48:03 +00:00
"fmt"
2017-12-05 13:28:42 +00:00
"reflect"
2017-12-03 13:54:09 +00:00
2017-12-05 13:28:42 +00:00
cda "git.loafle.net/commons_go/di/annotation"
2018-03-20 02:43:00 +00:00
cur "git.loafle.net/commons_go/util/reflect"
2017-12-05 13:28:42 +00:00
)
type TypeDefinition struct {
2017-12-06 00:48:03 +00:00
FullName string
2017-12-05 10:02:41 +00:00
PkgName string
TypeName string
Type reflect.Type
RealType reflect.Type
2017-12-05 13:28:42 +00:00
2018-03-15 13:19:44 +00:00
TypeAnnotations map[string]cda.Annotation
Fields []*FieldDefinition
}
func (td *TypeDefinition) GetAnnotation(name string) cda.Annotation {
if nil == td.TypeAnnotations {
return nil
}
2018-03-15 14:32:45 +00:00
2018-03-15 13:19:44 +00:00
return td.TypeAnnotations[name]
2017-12-05 13:28:42 +00:00
}
2018-03-15 14:32:45 +00:00
func (td *TypeDefinition) GetAnnotationByType(at reflect.Type, includeEmbedding bool) cda.Annotation {
if nil == td.TypeAnnotations {
return nil
}
for _, v := range td.TypeAnnotations {
2018-03-16 03:16:23 +00:00
if at == reflect.TypeOf(v) {
return v
}
2018-03-15 14:32:45 +00:00
if includeEmbedding {
if checkAnnotation(reflect.TypeOf(v), at) {
return v
}
}
}
return nil
}
func checkAnnotation(t reflect.Type, st reflect.Type) bool {
2018-03-20 02:43:00 +00:00
rt, _, _ := cur.GetTypeInfo(t)
2018-03-15 14:32:45 +00:00
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
}
2017-12-05 13:28:42 +00:00
type FieldDefinition struct {
2017-12-08 10:32:59 +00:00
FieldName string
PkgName string
TypeName string
Type reflect.Type
RealType reflect.Type
Annotations map[string]cda.Annotation
}
2017-12-05 13:28:42 +00:00
2017-12-08 10:32:59 +00:00
func (fd *FieldDefinition) GetAnnotation(name string) cda.Annotation {
if nil == fd.Annotations {
return nil
}
return fd.Annotations[name]
2017-12-03 13:54:09 +00:00
}
2017-12-06 00:48:03 +00:00
2018-03-16 03:16:23 +00:00
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
}
2017-12-06 00:48:03 +00:00
func FullName(pkgName, typeName string) string {
return fmt.Sprintf("%s/%s", pkgName, typeName)
}