Skip to content

Commit

Permalink
Merge pull request #8 from jjatria/validate-with
Browse files Browse the repository at this point in the history
Add support for validate_with [PRC]
  • Loading branch information
DrHyde committed Jul 11, 2018
2 parents 7e2ae02 + e462cfc commit f78a74b
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 1 deletion.
26 changes: 25 additions & 1 deletion lib/Params/Validate/Dependencies.pm
Expand Up @@ -37,7 +37,7 @@ foreach my $sub (@_of, 'exclusively') {

sub import {
# import all of P::V except validate()
Params::Validate->import(grep { $_ ne 'validate' } @Params::Validate::EXPORT_OK);
Params::Validate->import(grep { ! /^validate(_with)?$/ } @Params::Validate::EXPORT_OK);
# now export all that P::V would have exported, plus *_of
__PACKAGE__->export_to_level(1, @_);
}
Expand Down Expand Up @@ -139,6 +139,30 @@ sub validate (\@@) {
return wantarray ? %rval : \%rval;
}

=head2 validate_with
Overrides and extends Params::Validate's function of the same name.
=cut

sub validate_with {
my %args = @_;
my $params = [ @{$args{params}} ];

$args{dependencies} = [] unless defined $args{dependencies};

my %rval = Params::Validate::validate_with(@_);

my $coderefs = delete $args{dependencies};
$coderefs = ref($coderefs) eq 'ARRAY' ? $coderefs : [ $coderefs ];

foreach (@{$coderefs}) {
die("code-ref checking failed\n") unless($_->({@{$params}}));
}

return wantarray ? %rval : \%rval;
}

=head2 exclusively
Takes a single subref as its only argument (this would normally be the
Expand Down
61 changes: 61 additions & 0 deletions t/git-issue-2-validate-with.t
@@ -0,0 +1,61 @@
use strict;
use warnings;

use Params::Validate::Dependencies qw( validate_with all_of one_of );

use Test::More;
use Test::Exception;
END { done_testing(); }

sub doc { Params::Validate::Dependencies::document(@_) }

my $spec = { foo => 1, bar => 1, optional => 0 };

# Vanilla call
is_deeply +{
validate_with(
params => [ foo => 'foo', bar => 'bar', extra => 'extra' ],
spec => $spec,
allow_extra => 1,
),
},
{ foo => 'foo', bar => 'bar', extra => 'extra' },
'Vanilla call';

dies_ok {;
validate_with(
params => [ foo => 'foo', bar => 'bar' ],
spec => $spec,
dependencies => all_of(qw( foo optional )),
)
}
'Dies if dependency is not met';

is_deeply +{
validate_with(
params => [ foo => 'foo', bar => 'bar' ],
spec => $spec,
dependencies => [ one_of('foo'), one_of('bar') ],
)
},
{ foo => 'foo', bar => 'bar' },
'Supports multiple dependencies';

is_deeply +{
validate_with(
params => [ foo => 'foo', bar => 'bar' ],
spec => $spec,
)
},
{ foo => 'foo', bar => 'bar' },
'Lives without dependencies';

is_deeply +{
validate_with(
params => [ foo => 'foo', bar => 'bar', optional => 1 ],
spec => $spec,
dependencies => all_of(qw( foo optional )),
)
},
{ foo => 'foo', bar => 'bar', optional => 1 },
'Lives when dependency is met';

0 comments on commit f78a74b

Please sign in to comment.