Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Validator Bind can't cast value #336

Merged
merged 23 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 14 additions & 24 deletions validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import (
"errors"
"reflect"
"time"
"net/url"

"github.com/gookit/validate"

Expand All @@ -29,34 +28,25 @@
return nil, errors.New("rules can't be empty")
}

var dataType reflect.Kind
switch data := data.(type) {
var dataFace validate.DataFace
var err error
switch td := data.(type) {
case validate.DataFace:
hwbrzzl marked this conversation as resolved.
Show resolved Hide resolved
dataFace = td
case map[string]any:
if len(data) == 0 {
if len(td) == 0 {
return nil, errors.New("data can't be empty")
}
dataType = reflect.Map
}

val := reflect.ValueOf(data)
indirectVal := reflect.Indirect(val)
typ := indirectVal.Type()
if indirectVal.Kind() == reflect.Struct && typ != reflect.TypeOf(time.Time{}) {
dataType = reflect.Struct
}

var dataFace validate.DataFace
switch dataType {
case reflect.Map:
dataFace = validate.FromMap(data.(map[string]any))
case reflect.Struct:
var err error
dataFace = validate.FromMap(td)
case url.Values:
dataFace = validate.FromURLValues(td)
case map[string][]string:
hwbrzzl marked this conversation as resolved.
Show resolved Hide resolved
dataFace = validate.FromURLValues(td)

Check warning on line 44 in validation/validation.go

View check run for this annotation

Codecov / codecov/patch

validation/validation.go#L41-L44

Added lines #L41 - L44 were not covered by tests
default:
Comment on lines -32 to +45
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I refactored it by referring to the New method of github.com/gookit/validate

dataFace, err = validate.FromStruct(data)
if err != nil {
return nil, err
}
default:
return nil, errors.New("data must be map[string]any or struct")
devhaozi marked this conversation as resolved.
Show resolved Hide resolved
}

options = append(options, Rules(rules), CustomRules(r.rules))
Expand All @@ -70,7 +60,7 @@
v := dataFace.Create()
AppendOptions(v, generateOptions)

return NewValidator(v, dataFace), nil
return NewValidator(v), nil
}

func (r *Validation) AddRules(rules []validatecontract.Rule) error {
Expand Down
24 changes: 12 additions & 12 deletions validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestMake(t *testing.T) {
description: "error when data isn't map[string]any or struct",
data: "1",
rules: map[string]string{"a": "required"},
expectErr: errors.New("data must be map[string]any or struct"),
expectErr: errors.New("invalid input data"),
},
{
description: "error when data is empty map",
Expand Down Expand Up @@ -106,7 +106,7 @@ func TestMake(t *testing.T) {
}),
},
expectValidator: true,
expectData: Data{A: "c"},
expectData: Data{A: ""},
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now validator only Bind safe data, it meens validation must passed, so I change some test data.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to release this fix to v1.13.x, right? because it's a breaking change.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to release this fix to v1.13.x, right? because it's a breaking change.

Yes

expectErrors: true,
expectErrorMessage: "B can't be empty",
},
Expand Down Expand Up @@ -146,7 +146,7 @@ func TestMake(t *testing.T) {
}),
},
expectValidator: true,
expectData: Data{A: "c"},
expectData: Data{A: ""},
expectErrors: true,
expectErrorMessage: "b can't be empty",
},
Expand Down Expand Up @@ -2676,57 +2676,57 @@ func TestCustomRule(t *testing.T) {
type Uppercase struct {
}

//Signature The name of the rule.
// Signature The name of the rule.
func (receiver *Uppercase) Signature() string {
return "uppercase"
}

//Passes Determine if the validation rule passes.
// Passes Determine if the validation rule passes.
func (receiver *Uppercase) Passes(data httpvalidate.Data, val any, options ...any) bool {
name, exist := data.Get("name")

return strings.ToUpper(val.(string)) == val.(string) && len(val.(string)) == cast.ToInt(options[0]) && name == val && exist
}

//Message Get the validation error message.
// Message Get the validation error message.
func (receiver *Uppercase) Message() string {
return ":attribute must be upper"
}

type Lowercase struct {
}

//Signature The name of the rule.
// Signature The name of the rule.
func (receiver *Lowercase) Signature() string {
return "lowercase"
}

//Passes Determine if the validation rule passes.
// Passes Determine if the validation rule passes.
func (receiver *Lowercase) Passes(data httpvalidate.Data, val any, options ...any) bool {
address, exist := data.Get("address")

return strings.ToLower(val.(string)) == val.(string) && len(val.(string)) == cast.ToInt(options[0]) && address == val && exist
}

//Message Get the validation error message.
// Message Get the validation error message.
func (receiver *Lowercase) Message() string {
return ":attribute must be lower"
}

type Duplicate struct {
}

//Signature The name of the rule.
// Signature The name of the rule.
func (receiver *Duplicate) Signature() string {
return "required"
}

//Passes Determine if the validation rule passes.
// Passes Determine if the validation rule passes.
func (receiver *Duplicate) Passes(data httpvalidate.Data, val any, options ...any) bool {
return true
}

//Message Get the validation error message.
// Message Get the validation error message.
func (receiver *Duplicate) Message() string {
return ""
}
111 changes: 84 additions & 27 deletions validation/validator.go
devhaozi marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package validation

import (
"net/url"
"reflect"

"github.com/gookit/validate"
"github.com/mitchellh/mapstructure"
"github.com/spf13/cast"

httpvalidate "github.com/goravel/framework/contracts/validation"
)
Expand All @@ -12,48 +14,32 @@
validate.Config(func(opt *validate.GlobalOption) {
opt.StopOnError = false
opt.SkipOnEmpty = true
opt.FieldTag = "form"
})
}

type Validator struct {
instance *validate.Validation
data validate.DataFace
}

func NewValidator(instance *validate.Validation, data validate.DataFace) *Validator {
func NewValidator(instance *validate.Validation) *Validator {
instance.Validate()

return &Validator{instance: instance, data: data}
return &Validator{instance: instance}
}

func (v *Validator) Bind(ptr any) error {
var data any
if _, ok := v.data.Src().(url.Values); ok {
values := make(map[string]any)
for key, value := range v.data.Src().(url.Values) {
if len(value) > 0 {
values[key] = value[0]
}
}

formData, ok := v.data.(*validate.FormData)
if ok {
for key, value := range formData.Files {
values[key] = value
}
}

data = values
} else {
data = v.data.Src()
}

bts, err := validate.Marshal(data)
data := v.instance.SafeData()
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "form",
Result: &ptr,
DecodeHook: v.castValue(),
})
if err != nil {
return err
}

return validate.Unmarshal(bts, ptr)
return decoder.Decode(data)
}

func (v *Validator) Errors() httpvalidate.Errors {
Expand All @@ -67,3 +53,74 @@
func (v *Validator) Fails() bool {
return v.instance.IsFail()
}

func (v *Validator) castValue() mapstructure.DecodeHookFunc {
devhaozi marked this conversation as resolved.
Show resolved Hide resolved
return func(from reflect.Value, to reflect.Value) (any, error) {
var castedValue any
var err error

switch to.Kind() {
case reflect.String:
castedValue = cast.ToString(from.Interface())
case reflect.Int:
castedValue, err = cast.ToIntE(from.Interface())
case reflect.Int8:
castedValue, err = cast.ToInt8E(from.Interface())
case reflect.Int16:
castedValue, err = cast.ToInt16E(from.Interface())
case reflect.Int32:
castedValue, err = cast.ToInt32E(from.Interface())
case reflect.Int64:
castedValue, err = cast.ToInt64E(from.Interface())
case reflect.Uint:
castedValue, err = cast.ToUintE(from.Interface())
case reflect.Uint8:
castedValue, err = cast.ToUint8E(from.Interface())
case reflect.Uint16:
castedValue, err = cast.ToUint16E(from.Interface())
case reflect.Uint32:
castedValue, err = cast.ToUint32E(from.Interface())
case reflect.Uint64:
castedValue, err = cast.ToUint64E(from.Interface())
case reflect.Bool:
castedValue, err = cast.ToBoolE(from.Interface())
case reflect.Float32:
castedValue, err = cast.ToFloat32E(from.Interface())
case reflect.Float64:
castedValue, err = cast.ToFloat64E(from.Interface())
case reflect.Slice, reflect.Array:
switch to.Type().Elem().Kind() {
case reflect.String:
castedValue, err = cast.ToStringSliceE(from.Interface())
case reflect.Int:
castedValue, err = cast.ToIntSliceE(from.Interface())
case reflect.Bool:
castedValue, err = cast.ToBoolSliceE(from.Interface())
default:
castedValue, err = cast.ToSliceE(from.Interface())

Check warning on line 100 in validation/validator.go

View check run for this annotation

Codecov / codecov/patch

validation/validator.go#L95-L100

Added lines #L95 - L100 were not covered by tests
}
case reflect.Map:
switch to.Type().Key().Kind() {
case reflect.String:
castedValue, err = cast.ToStringMapStringE(from.Interface())
case reflect.Bool:
castedValue, err = cast.ToStringMapBoolE(from.Interface())
case reflect.Int:
castedValue, err = cast.ToStringMapIntE(from.Interface())
case reflect.Int64:
castedValue, err = cast.ToStringMapInt64E(from.Interface())
default:
castedValue, err = cast.ToStringMapE(from.Interface())

Check warning on line 113 in validation/validator.go

View check run for this annotation

Codecov / codecov/patch

validation/validator.go#L106-L113

Added lines #L106 - L113 were not covered by tests
}
default:
castedValue = from.Interface()
}

// Only return casted value if there was no error
if err == nil {
return castedValue, nil
}

return from.Interface(), nil

Check warning on line 124 in validation/validator.go

View check run for this annotation

Codecov / codecov/patch

validation/validator.go#L124

Added line #L124 was not covered by tests
}
}
Loading