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