diff options
author | Yorhel <git@yorhel.nl> | 2018-04-15 10:11:09 +0200 |
---|---|---|
committer | Yorhel <git@yorhel.nl> | 2018-04-15 10:11:11 +0200 |
commit | 1b0025f3140f5ef97a4222784cf2a38aa471d941 (patch) | |
tree | 3d4fa173d8ac1fd1d0bbce2415edf95ad4819bf9 /lib/TUWF/Misc.pm | |
parent | fe5943688e9339e46cbec20a93f3ceb80d5d8f01 (diff) |
Integrate TUWF::Validate with the rest of TUWF
- Add a 'custom_validations' setting
- Add tuwf->compile() to compile with that setting
- Add tuwf->validate() as alternative to formValidate()
The new tuwf->validate() uses internal state of TUWF::Request, which had
to be changed a bit to allow for more efficient validation.
Nested schemas in TUWF::Validate now also accept compiled schemas.
This stuff totally needs more documentation.
Diffstat (limited to 'lib/TUWF/Misc.pm')
-rw-r--r-- | lib/TUWF/Misc.pm | 43 |
1 files changed, 40 insertions, 3 deletions
diff --git a/lib/TUWF/Misc.pm b/lib/TUWF/Misc.pm index 91b3ae2..edea8de 100644 --- a/lib/TUWF/Misc.pm +++ b/lib/TUWF/Misc.pm @@ -13,7 +13,6 @@ use TUWF::Validate; our $VERSION = '1.2'; -our @EXPORT = ('formValidate', 'mail'); our @EXPORT_OK = ('uri_escape', 'kv_validate'); @@ -148,7 +147,7 @@ sub _validate { # value, \%templates, \%rules -sub formValidate { +sub TUWF::Object::formValidate { my($self, @fields) = @_; return kv_validate( { post => sub { $self->reqPosts(shift) }, @@ -164,7 +163,7 @@ sub formValidate { # A simple mail function, body and headers as arguments. Usage: # $self->mail('body', header1 => 'value of header 1', ..); -sub mail { +sub TUWF::Object::mail { my $self = shift; my $body = shift; my %hs = @_; @@ -192,4 +191,42 @@ sub mail { } +sub TUWF::Object::compile { + TUWF::Validate::compile($_[0]{_TUWF}{custom_validations}, $_[1]); +} + + +sub _compile { + ref $_[0] eq 'TUWF::Validate' ? $_[0] : $TUWF::OBJ->compile($_[0]); +} + + +sub TUWF::Object::validate { + my $self = shift; + my $what = shift; + + return _compile($_[0])->validate($self->reqJSON) if $what eq 'json'; + + # 'param' is special, and not really encouraged. Create a new hash based on + # reqParam() and cache the result. + $self->{_TUWF}{Req}{PARAM} ||= { + map { my @v = $self->reqParams($_); +($_, @v > 1 ? \@v : $v[0]) } $self->reqParams() + } if $what eq 'param'; + + my $source = + $what eq 'get' ? $self->{_TUWF}{Req}{GET} : + $what eq 'post' ? $self->{_TUWF}{Req}{POST} : + $what eq 'param' ? $self->{_TUWF}{Req}{PARAM} + : croak "Invalid source type '$what'"; + + # Multi-value, schema hash or object + return _compile($_[0])->validate($source) if @_ == 1; + + # Single value + return _compile($_[1])->validate($source->{$_[0]}) if @_ == 2; + + # Multi-value, separate params + _comile({ @_ })->validate($source); +} + 1; |