-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmapper_object_internal.go
369 lines (343 loc) · 9.78 KB
/
mapper_object_internal.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package mapper
import (
"errors"
"fmt"
"reflect"
"strings"
"sync"
"time"
)
// registerValue register Value to init Map
func (dm *mapperObject) registerValue(objValue reflect.Value) error {
regValue := objValue
if objValue == dm.ZeroValue {
return errors.New("obj value does not exist")
}
if regValue.Type().Kind() == reflect.Ptr {
regValue = regValue.Elem()
}
typeName := regValue.Type().String()
if regValue.Type().Kind() == reflect.Struct {
for i := 0; i < regValue.NumField(); i++ {
fieldName := dm.getFieldName(regValue, i)
if fieldName == IgnoreTagValue {
continue
}
mapFieldName := typeName + nameConnector + fieldName
realFieldName := regValue.Type().Field(i).Name
dm.fieldNameMap.Store(mapFieldName, realFieldName)
}
}
// store register flag
dm.registerMap.Store(typeName, nil)
return nil
}
// cleanRegisterValue clean all register Value & field name map
func (dm *mapperObject) cleanRegisterValue() {
dm.registerMap = *new(sync.Map)
dm.fieldNameMap = *new(sync.Map)
}
// GetFieldName get fieldName with ElemValue and index
// if config tag string, return tag value
func (dm *mapperObject) getFieldName(objElem reflect.Value, index int) string {
fieldName := ""
field := objElem.Type().Field(index)
tag := dm.getStructTag(field)
// keeps the behavior in old version
if tag == IgnoreTagValue && !dm.IsEnableFieldIgnoreTag() {
tag = ""
}
if tag != "" {
fieldName = tag
} else {
fieldName = field.Name
}
return fieldName
}
// UseWrapper register a type wrapper
func (dm *mapperObject) useWrapper(w TypeWrapper) {
if len(dm.typeWrappers) > 0 {
dm.typeWrappers[len(dm.typeWrappers)-1].SetNext(w)
}
dm.typeWrappers = append(dm.typeWrappers, w)
}
func (dm *mapperObject) elemMapper(fromElem, toElem reflect.Value) error {
// check register flag
// if not register, register it
if !dm.checkIsRegister(fromElem) {
if err := dm.registerValue(fromElem); err != nil {
return err
}
}
if !dm.checkIsRegister(toElem) {
if err := dm.registerValue(toElem); err != nil {
return err
}
}
if toElem.Type().Kind() == reflect.Map {
dm.elemToMap(fromElem, toElem)
} else {
dm.elemToStruct(fromElem, toElem)
}
return nil
}
// elemToStruct to convert the different structs for assignment.
func (dm *mapperObject) elemToStruct(fromElem, toElem reflect.Value) {
for i := 0; i < fromElem.NumField(); i++ {
fromFieldInfo := fromElem.Field(i)
fieldName := dm.getFieldName(fromElem, i)
if fieldName == IgnoreTagValue {
continue
}
if fieldName == CompositeFieldTagValue &&
fromFieldInfo.Kind() == reflect.Struct {
//If composite fields are identified, further decomposition and judgment will be taken.
fromElem := fromFieldInfo
for i := 0; i < fromElem.NumField(); i++ {
fromFieldInfo := fromElem.Field(i)
fieldName := dm.getFieldName(fromElem, i)
if fieldName == IgnoreTagValue {
continue
}
err := dm.convertstructfieldInternal(fieldName, fromFieldInfo, toElem)
if err != nil {
fmt.Println("auto mapper failed", fromFieldInfo, "error", err.Error())
}
}
} else {
err := dm.convertstructfieldInternal(fieldName, fromFieldInfo, toElem)
if err != nil {
fmt.Println("auto mapper failed", fromFieldInfo, "error", err.Error())
}
}
}
}
// convertstructfieldInternal to convert the fields of different structs for assignment.
func (dm *mapperObject) convertstructfieldInternal(fieldName string, fromFieldInfo, toElem reflect.Value) error {
// check field is exists
realFieldName, exists := dm.CheckExistsField(toElem, fieldName)
if !exists {
return nil
}
toFieldInfo := toElem.FieldByName(realFieldName)
// check field is same type
if dm.setting.EnabledTypeChecking {
if fromFieldInfo.Kind() != toFieldInfo.Kind() {
return nil
}
}
if dm.setting.EnabledMapperStructField &&
toFieldInfo.Kind() == reflect.Struct && fromFieldInfo.Kind() == reflect.Struct &&
toFieldInfo.Type() != fromFieldInfo.Type() &&
!dm.checkIsTypeWrapper(toFieldInfo) && !dm.checkIsTypeWrapper(fromFieldInfo) {
x := reflect.New(toFieldInfo.Type()).Elem()
err := dm.elemMapper(fromFieldInfo, x)
if err != nil {
return err
} else {
toFieldInfo.Set(x)
}
} else {
isSet := false
if dm.setting.EnabledAutoTypeConvert {
if dm.DefaultTimeWrapper.IsType(fromFieldInfo) && toFieldInfo.Kind() == reflect.Int64 {
fromTime := fromFieldInfo.Interface().(time.Time)
toFieldInfo.Set(reflect.ValueOf(TimeToUnix(fromTime)))
isSet = true
} else if dm.DefaultTimeWrapper.IsType(toFieldInfo) && fromFieldInfo.Kind() == reflect.Int64 {
fromTime := fromFieldInfo.Interface().(int64)
toFieldInfo.Set(reflect.ValueOf(UnixToTime(fromTime)))
isSet = true
}
}
if !isSet {
toFieldInfo.Set(fromFieldInfo)
}
}
return nil
}
func (dm *mapperObject) elemToMap(fromElem, toElem reflect.Value) {
for i := 0; i < fromElem.NumField(); i++ {
fromFieldInfo := fromElem.Field(i)
fieldName := dm.getFieldName(fromElem, i)
if fieldName == IgnoreTagValue {
continue
}
toElem.SetMapIndex(reflect.ValueOf(fieldName), fromFieldInfo)
}
}
func (dm *mapperObject) setFieldValue(fieldValue reflect.Value, fieldKind reflect.Kind, value interface{}) error {
switch fieldKind {
case reflect.Bool:
if value == nil {
fieldValue.SetBool(false)
} else if v, ok := value.(bool); ok {
fieldValue.SetBool(v)
} else {
v, _ := Convert(ToString(value)).Bool()
fieldValue.SetBool(v)
}
case reflect.String:
if value == nil {
fieldValue.SetString("")
} else {
fieldValue.SetString(ToString(value))
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if value == nil {
fieldValue.SetInt(0)
} else {
val := reflect.ValueOf(value)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fieldValue.SetInt(val.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
fieldValue.SetInt(int64(val.Uint()))
default:
v, _ := Convert(ToString(value)).Int64()
fieldValue.SetInt(v)
}
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if value == nil {
fieldValue.SetUint(0)
} else {
val := reflect.ValueOf(value)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fieldValue.SetUint(uint64(val.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
fieldValue.SetUint(val.Uint())
default:
v, _ := Convert(ToString(value)).Uint64()
fieldValue.SetUint(v)
}
}
case reflect.Float64, reflect.Float32:
if value == nil {
fieldValue.SetFloat(0)
} else {
val := reflect.ValueOf(value)
switch val.Kind() {
case reflect.Float64:
fieldValue.SetFloat(val.Float())
default:
v, _ := Convert(ToString(value)).Float64()
fieldValue.SetFloat(v)
}
}
case reflect.Struct:
if value == nil {
fieldValue.Set(reflect.Zero(fieldValue.Type()))
} else if dm.DefaultTimeWrapper.IsType(fieldValue) {
var timeString string
if fieldValue.Type() == dm.timeType {
timeString = ""
fieldValue.Set(reflect.ValueOf(value))
}
if fieldValue.Type() == dm.jsonTimeType {
timeString = ""
fieldValue.Set(reflect.ValueOf(JSONTime(value.(time.Time))))
}
switch d := value.(type) {
case []byte:
timeString = string(d)
case string:
timeString = d
case int64:
if dm.setting.EnabledAutoTypeConvert {
// try to transform Unix time to local Time
t, err := UnixToTimeLocation(value.(int64), time.UTC.String())
if err != nil {
return err
}
fieldValue.Set(reflect.ValueOf(t))
}
}
if timeString != "" {
if len(timeString) >= 19 {
// 满足yyyy-MM-dd HH:mm:ss格式
timeString = timeString[:19]
t, err := time.ParseInLocation(formatDateTime, timeString, time.UTC)
if err == nil {
t = t.In(time.UTC)
fieldValue.Set(reflect.ValueOf(t))
}
} else if len(timeString) >= 10 {
// 满足yyyy-MM-dd格式
timeString = timeString[:10]
t, err := time.ParseInLocation(formatDate, timeString, time.UTC)
if err == nil {
fieldValue.Set(reflect.ValueOf(t))
}
}
}
}
default:
if reflect.ValueOf(value).Type() == fieldValue.Type() {
fieldValue.Set(reflect.ValueOf(value))
}
}
return nil
}
func (dm *mapperObject) getStructTag(field reflect.StructField) string {
tagValue := ""
// 1.check mapperTagKey
if dm.setting.EnabledMapperTag {
tagValue = field.Tag.Get(mapperTagKey)
if tagValue != "" {
return tagValue
}
}
// 2.check jsonTagKey
if dm.setting.EnabledJsonTag {
tagValue = field.Tag.Get(jsonTagKey)
if tagValue != "" {
// support more tag property, as json tag omitempty 2018-07-13
return strings.Split(tagValue, ",")[0]
}
}
// 3.che
// ck customTag
if dm.setting.EnabledCustomTag {
tagValue = field.Tag.Get(dm.setting.CustomTagName)
if tagValue != "" {
return tagValue
}
}
return tagValue
}
func (dm *mapperObject) checkIsRegister(objElem reflect.Value) bool {
typeName := objElem.Type().String()
_, isOk := dm.registerMap.Load(typeName)
return isOk
}
// convertToSlice convert slice interface{} to []interface{}
func (dm *mapperObject) convertToSlice(arr interface{}) []interface{} {
v := reflect.ValueOf(arr)
if v.Kind() == reflect.Ptr {
if v.Elem().Kind() != reflect.Slice {
panic("fromSlice arr is not a pointer to a slice")
}
v = v.Elem()
} else {
if v.Kind() != reflect.Slice {
panic("fromSlice arr is not a slice")
}
}
l := v.Len()
ret := make([]interface{}, l)
for i := 0; i < l; i++ {
ret[i] = v.Index(i).Interface()
}
return ret
}
// checkIsTypeWrapper check value is in type wrappers
func (dm *mapperObject) checkIsTypeWrapper(value reflect.Value) bool {
for _, w := range dm.typeWrappers {
if w.IsType(value) {
return true
}
}
return false
}