github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/validate/matcher/value.go (about) 1 package matcher 2 3 import ( 4 "fmt" 5 "github.com/isyscore/isc-gobase/constants" 6 "reflect" 7 "strings" 8 9 "github.com/isyscore/isc-gobase/logger" 10 ) 11 12 type ValueMatch struct { 13 BlackWhiteMatch 14 Values []any 15 } 16 17 func (valueMatch *ValueMatch) Match(_ map[string]interface{}, _ any, field reflect.StructField, fieldValue any) bool { 18 values := valueMatch.Values 19 20 fieldRelValue := fieldValue 21 if reflect.TypeOf(fieldValue).Kind() == reflect.Ptr { 22 fieldRelValue = reflect.ValueOf(fieldValue).Elem() 23 } 24 25 for _, value := range values { 26 if fmt.Sprintf("%v", value) == fmt.Sprintf("%v", fieldRelValue) { 27 valueMatch.SetBlackMsg("属性 %v 的值 %v 位于禁用值 %v 中", field.Name, fieldRelValue, values) 28 return true 29 } 30 } 31 valueMatch.SetWhiteMsg("属性 %v 的值 %v 不在只可用列表 %v 中", field.Name, fieldRelValue, values) 32 return false 33 } 34 35 func (valueMatch *ValueMatch) IsEmpty() bool { 36 return len(valueMatch.Values) == 0 37 } 38 39 func BuildValuesMatcher(objectTypeFullName string, fieldKind reflect.Kind, objectFieldName string, tagName string, subCondition string, errMsg string) { 40 if constants.MATCH != tagName { 41 return 42 } 43 44 if fieldKind == reflect.Slice { 45 return 46 } 47 if !strings.Contains(subCondition, constants.Value) || !strings.Contains(subCondition, constants.EQUAL) { 48 return 49 } 50 51 index := strings.Index(subCondition, "=") 52 value := subCondition[index+1:] 53 54 var availableValues []any 55 value = strings.TrimSpace(value) 56 if strings.HasPrefix(value, "{") && strings.HasSuffix(value, "}") { 57 value = value[1 : len(value)-1] 58 for _, subValue := range strings.Split(value, ",") { 59 subValue = strings.TrimSpace(subValue) 60 if chgValue, err := Cast(fieldKind, subValue); err == nil { 61 availableValues = append(availableValues, chgValue) 62 } else { 63 logger.Error(err.Error()) 64 continue 65 } 66 } 67 } else { 68 value = strings.TrimSpace(value) 69 if chgValue, err := Cast(fieldKind, value); err == nil { 70 availableValues = append(availableValues, chgValue) 71 } else { 72 logger.Error(err.Error()) 73 return 74 } 75 } 76 addMatcher(objectTypeFullName, objectFieldName, &ValueMatch{Values: availableValues}, errMsg, true) 77 }