github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/validate/matcher/isUnBlank.go (about)

     1  package matcher
     2  
     3  import (
     4  	"github.com/isyscore/isc-gobase/constants"
     5  	"reflect"
     6  	"strconv"
     7  	"strings"
     8  
     9  	"github.com/isyscore/isc-gobase/logger"
    10  )
    11  
    12  type IsUnBlankMatch struct {
    13  	BlackWhiteMatch
    14  
    15  	// 是否设置过isNil值
    16  	HaveSet int8
    17  
    18  	// 匹配非空的值
    19  	IsUnBlank bool
    20  }
    21  
    22  func (isUnBlankMatch *IsUnBlankMatch) Match(_ map[string]interface{}, _ any, field reflect.StructField, fieldValue any) bool {
    23  	if reflect.TypeOf(fieldValue).Kind() != field.Type.Kind() {
    24  		isUnBlankMatch.SetBlackMsg("属性 %v 的值不是字符类型", field.Name)
    25  		return false
    26  	}
    27  
    28  	if isUnBlankMatch.IsUnBlank {
    29  		if fieldValue != "" {
    30  			isUnBlankMatch.SetBlackMsg("属性 %v 的值为空字符", field.Name)
    31  			return true
    32  		} else {
    33  			isUnBlankMatch.SetWhiteMsg("属性 %v 的值为非空字符", field.Name)
    34  			return false
    35  		}
    36  	} else {
    37  		if fieldValue == "" {
    38  			isUnBlankMatch.SetBlackMsg("属性 %v 的值不为空", field.Name)
    39  			return true
    40  		} else {
    41  			isUnBlankMatch.SetWhiteMsg("属性 %v 的值为空字符", field.Name)
    42  			return false
    43  		}
    44  	}
    45  }
    46  
    47  func (isUnBlankMatch *IsUnBlankMatch) IsEmpty() bool {
    48  	return isUnBlankMatch.HaveSet == 0
    49  }
    50  
    51  func BuildIsUnBlankMatcher(objectTypeFullName string, fieldKind reflect.Kind, objectFieldName string, tagName string, subCondition string, errMsg string) {
    52  	if constants.MATCH != tagName {
    53  		return
    54  	}
    55  
    56  	if fieldKind == reflect.Slice {
    57  		return
    58  	}
    59  
    60  	if !strings.Contains(subCondition, constants.IsUnBlank) {
    61  		return
    62  	}
    63  
    64  	value := "true"
    65  	if strings.Contains(subCondition, constants.EQUAL) {
    66  		index := strings.Index(subCondition, "=")
    67  		value = strings.TrimSpace(subCondition[index+1:])
    68  	}
    69  
    70  	if strings.EqualFold("true", value) || strings.EqualFold("false", value) {
    71  		var isUnBlank bool
    72  		if chgValue, err := strconv.ParseBool(value); err == nil {
    73  			isUnBlank = chgValue
    74  		} else {
    75  			logger.Error(err.Error())
    76  			return
    77  		}
    78  		addMatcher(objectTypeFullName, objectFieldName, &IsUnBlankMatch{IsUnBlank: isUnBlank, HaveSet: 1}, errMsg, true)
    79  	}
    80  }