github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_enums.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"reflect"
    13  
    14  	"github.com/gogf/gf/v2/errors/gcode"
    15  	"github.com/gogf/gf/v2/errors/gerror"
    16  	"github.com/gogf/gf/v2/internal/json"
    17  	"github.com/gogf/gf/v2/text/gstr"
    18  	"github.com/gogf/gf/v2/util/gconv"
    19  	"github.com/gogf/gf/v2/util/gtag"
    20  )
    21  
    22  // RuleEnums implements `enums` rule:
    23  // Value should be in enums of its constant type.
    24  //
    25  // Format: enums
    26  type RuleEnums struct{}
    27  
    28  func init() {
    29  	Register(RuleEnums{})
    30  }
    31  
    32  func (r RuleEnums) Name() string {
    33  	return "enums"
    34  }
    35  
    36  func (r RuleEnums) Message() string {
    37  	return "The {field} value `{value}` should be in enums of: {enums}"
    38  }
    39  
    40  func (r RuleEnums) Run(in RunInput) error {
    41  	if in.ValueType == nil {
    42  		return gerror.NewCode(
    43  			gcode.CodeInvalidParameter,
    44  			`value type cannot be empty to use validation rule "enums"`,
    45  		)
    46  	}
    47  	var (
    48  		pkgPath  = in.ValueType.PkgPath()
    49  		typeName = in.ValueType.Name()
    50  	)
    51  	if in.ValueType.Kind() == reflect.Slice {
    52  		pkgPath = in.ValueType.Elem().PkgPath()
    53  		typeName = in.ValueType.Elem().Name()
    54  	}
    55  	if pkgPath == "" {
    56  		return gerror.NewCodef(
    57  			gcode.CodeInvalidOperation,
    58  			`no pkg path found for type "%s"`,
    59  			in.ValueType.String(),
    60  		)
    61  	}
    62  	var (
    63  		typeId   = fmt.Sprintf(`%s.%s`, pkgPath, typeName)
    64  		tagEnums = gtag.GetEnumsByType(typeId)
    65  	)
    66  	if tagEnums == "" {
    67  		return gerror.NewCodef(
    68  			gcode.CodeInvalidOperation,
    69  			`no enums found for type "%s", missing using command "gf gen enums"?`,
    70  			typeId,
    71  		)
    72  	}
    73  	var enumsValues = make([]interface{}, 0)
    74  	if err := json.Unmarshal([]byte(tagEnums), &enumsValues); err != nil {
    75  		return err
    76  	}
    77  	if !gstr.InArray(gconv.Strings(enumsValues), in.Value.String()) {
    78  		return errors.New(gstr.Replace(
    79  			in.Message, `{enums}`, tagEnums,
    80  		))
    81  	}
    82  	return nil
    83  }