valuer.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package mapping
  2. type (
  3. // A Valuer interface defines the way to get values from the underlying object with keys.
  4. Valuer interface {
  5. // Value gets the value associated with the given key.
  6. Value(key string) (interface{}, bool)
  7. }
  8. // A valuerWithParent defines a node that has a parent node.
  9. valuerWithParent interface {
  10. Valuer
  11. // Parent get the parent valuer for current node.
  12. Parent() valuerWithParent
  13. }
  14. // A node is a map that can use Value method to get values with given keys.
  15. node struct {
  16. current Valuer
  17. parent valuerWithParent
  18. }
  19. // A valueWithParent is used to wrap the value with its parent.
  20. valueWithParent struct {
  21. value interface{}
  22. parent valuerWithParent
  23. }
  24. // mapValuer is a type for map to meet the Valuer interface.
  25. mapValuer map[string]interface{}
  26. // simpleValuer is a type to get value from current node.
  27. simpleValuer node
  28. // recursiveValuer is a type to get the value recursively from current and parent nodes.
  29. recursiveValuer node
  30. )
  31. // Value gets the value assciated with the given key from mv.
  32. func (mv mapValuer) Value(key string) (interface{}, bool) {
  33. v, ok := mv[key]
  34. return v, ok
  35. }
  36. // Value gets the value associated with the given key from sv.
  37. func (sv simpleValuer) Value(key string) (interface{}, bool) {
  38. v, ok := sv.current.Value(key)
  39. return v, ok
  40. }
  41. // Parent get the parent valuer from sv.
  42. func (sv simpleValuer) Parent() valuerWithParent {
  43. if sv.parent == nil {
  44. return nil
  45. }
  46. return recursiveValuer{
  47. current: sv.parent,
  48. parent: sv.parent.Parent(),
  49. }
  50. }
  51. // Value gets the value associated with the given key from rv,
  52. // and it will inherit the value from parent nodes.
  53. func (rv recursiveValuer) Value(key string) (interface{}, bool) {
  54. val, ok := rv.current.Value(key)
  55. if !ok {
  56. if parent := rv.Parent(); parent != nil {
  57. return parent.Value(key)
  58. }
  59. return nil, false
  60. }
  61. if vm, ok := val.(map[string]interface{}); ok {
  62. if parent := rv.Parent(); parent != nil {
  63. pv, pok := parent.Value(key)
  64. if pok {
  65. if pm, ok := pv.(map[string]interface{}); ok {
  66. for k, v := range vm {
  67. pm[k] = v
  68. }
  69. return pm, true
  70. }
  71. }
  72. }
  73. }
  74. return val, true
  75. }
  76. // Parent get the parent valuer from rv.
  77. func (rv recursiveValuer) Parent() valuerWithParent {
  78. if rv.parent == nil {
  79. return nil
  80. }
  81. return recursiveValuer{
  82. current: rv.parent,
  83. parent: rv.parent.Parent(),
  84. }
  85. }