-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
checks, form configuration, refactored field toward eventual function…
… configuration, new errors, general refactoring
- Loading branch information
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package fork | ||
|
||
import "reflect" | ||
|
||
type Checker interface { | ||
Valid(Form) bool | ||
Check(Form) (bool, error) | ||
Checks(...interface{}) []reflect.Value | ||
} | ||
|
||
type checker struct { | ||
checks []reflect.Value | ||
} | ||
|
||
func NewChecker() Checker { | ||
return &checker{} | ||
} | ||
|
||
func (c *checker) Valid(f Form) bool { | ||
for _, fd := range f.Fields() { | ||
if !fd.Valid(fd) { | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
|
||
func (c *checker) Check(f Form) (bool, error) { | ||
var err error | ||
var valid bool | ||
for _, fn := range c.checks { | ||
valid, err = Check(fn, f) | ||
if err != nil { | ||
return valid, err | ||
} | ||
} | ||
return valid, err | ||
} | ||
|
||
func (c *checker) Checks(fns ...interface{}) []reflect.Value { | ||
for _, fn := range fns { | ||
c.AddCheck(fn) | ||
} | ||
return c.checks | ||
} | ||
|
||
func (c *checker) AddCheck(fn interface{}) { | ||
c.checks = append(c.checks, valueFn(fn, `must return 1 boolean and 1 error`)) | ||
} | ||
|
||
var boolType = reflect.TypeOf((*bool)(nil)).Elem() | ||
|
||
func isCheck(typ reflect.Type) bool { | ||
switch { | ||
case typ.NumOut() == 2 && typ.Out(0) == boolType && typ.Out(1) == errorType: | ||
return true | ||
} | ||
return false | ||
} | ||
|
||
var BadCheck = ForkError(`[fork] check function did not return a boolean value with its error.`) | ||
|
||
func Check(fn reflect.Value, args ...interface{}) (bool, error) { | ||
checked, err := call(fn, args...) | ||
if checked, ok := checked.(bool); ok { | ||
return checked, err | ||
} | ||
return false, BadCheck | ||
} |