github.com/wangyougui/gf/v2@v2.6.5/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/wangyougui/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  
    13  	"github.com/wangyougui/gf/v2/errors/gcode"
    14  	"github.com/wangyougui/gf/v2/errors/gerror"
    15  	"github.com/wangyougui/gf/v2/internal/json"
    16  	"github.com/wangyougui/gf/v2/text/gstr"
    17  	"github.com/wangyougui/gf/v2/util/gconv"
    18  	"github.com/wangyougui/gf/v2/util/gtag"
    19  )
    20  
    21  // RuleEnums implements `enums` rule:
    22  // Value should be in enums of its constant type.
    23  //
    24  // Format: enums
    25  type RuleEnums struct{}
    26  
    27  func init() {
    28  	Register(RuleEnums{})
    29  }
    30  
    31  func (r RuleEnums) Name() string {
    32  	return "enums"
    33  }
    34  
    35  func (r RuleEnums) Message() string {
    36  	return "The {field} value `{value}` should be in enums of: {enums}"
    37  }
    38  
    39  func (r RuleEnums) Run(in RunInput) error {
    40  	if in.ValueType == nil {
    41  		return gerror.NewCode(
    42  			gcode.CodeInvalidParameter,
    43  			`value type cannot be empty to use validation rule "enums"`,
    44  		)
    45  	}
    46  	var (
    47  		pkgPath  = in.ValueType.PkgPath()
    48  		typeName = in.ValueType.Name()
    49  	)
    50  	if pkgPath == "" {
    51  		return gerror.NewCodef(
    52  			gcode.CodeInvalidOperation,
    53  			`no pkg path found for type "%s"`,
    54  			in.ValueType.String(),
    55  		)
    56  	}
    57  	var (
    58  		typeId   = fmt.Sprintf(`%s.%s`, pkgPath, typeName)
    59  		tagEnums = gtag.GetEnumsByType(typeId)
    60  	)
    61  	if tagEnums == "" {
    62  		return gerror.NewCodef(
    63  			gcode.CodeInvalidOperation,
    64  			`no enums found for type "%s", missing using command "gf gen enums"?`,
    65  			typeId,
    66  		)
    67  	}
    68  	var enumsValues = make([]interface{}, 0)
    69  	if err := json.Unmarshal([]byte(tagEnums), &enumsValues); err != nil {
    70  		return err
    71  	}
    72  	if !gstr.InArray(gconv.Strings(enumsValues), in.Value.String()) {
    73  		return errors.New(gstr.Replace(
    74  			in.Message, `{enums}`, tagEnums,
    75  		))
    76  	}
    77  	return nil
    78  }