package Params::Validate::Dependencies;

use strict;
use warnings;

use Clone qw(clone);
use Params::Validate (); # don't import yet
use Params::Validate::Dependencies::Documenter;
use Scalar::Util qw(blessed);
use PadWalker qw(closed_over);

use base qw(Exporter);


$VERSION = '1.40';
$DOC = 0;

# copy and update P::V's EXPORT* constants
my @_of = qw(any_of all_of none_of one_of);
@EXPORT = (@Params::Validate::EXPORT, @_of);
@EXPORT_OK = (@Params::Validate::EXPORT_OK, @_of, 'exclusively');
%EXPORT_TAGS = (%{clone(\%Params::Validate::EXPORT_TAGS)}, _of => \@_of);
push @{$EXPORT_TAGS{all}}, (@_of, 'exclusively');

# because repeating the call to _validate_factory_args everywhere is BAD
foreach my $sub (@_of, 'exclusively') {
  no strict 'refs';
  no warnings 'redefine';
  my $orig = \&{$sub};
  *{$sub} = sub {
    local *__ANON__ = $sub;

sub import {
  # import all of P::V except validate() and dvalidate_with()
  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, @_);

=head1 NAME

Params::Validate::Dependencies - check that the right combination of arguments is passed to a function


Extends Params::Validate to make it easy to validate
that you have been passed the correct combinations of parameters.


This example validates that sub 'foo's arguments are of the right types,
and that either we have at least one of alpha, beta and gamma, or
we have both of bar amd baz:

  use Params::Validate::Dependencies qw(:all);

  sub foo {
        alpha => { type => ARRAYREF, optional => 1 },
        beta  => { type => ARRAYREF, optional => 1 },
        gamma => { type => ARRAYREF, optional => 1 },
        bar   => { type => SCALAR, optional => 1 },
        baz   => { type => SCALAR, optional => 1 },
        qw(alpha beta gamma),
        all_of(qw(bar baz)),


Params::Validate::Dependencies extends Params::Validate's
validate() function to
support an arbitrary number of callbacks which are not associated
with any one parameter.  All of those callbacks are run after
Params::Validate's normal validate() function.  
If any of them return false, then validate() will die as normal.


All of the *_of functions are exported by default in addition to those
exported by default by Params::Validate.  They are also available with the
tag ':_of' in case you want to use them without Params::Validate.
In that case you would load the module thus:

  use Params::Validate::Dependencies qw(:_of);

All of the *_of functions take a list of scalars and code-refs and
return a code-ref (which is a closure over the list originally passed
to the function) suitable for use in validate() or in another *_of
function.  All code-refs should take as their only argument a hashref
of parameters to check, returning true if the parameters are good
and false otherwise.

=head2 document

This takes a code-ref argument as generated by a tree of *_of calls,
and spits out some documentation of it.  This function is not exported.


sub document {
  my $sub = shift;
  die(__PACKAGE__."::document: object $sub is wrong type\n")
    unless(blessed($sub) && $sub->can('_document'));

=head2 validate

Overrides and extends Params::Validate's function of the same name.


sub validate (\@@) {
  my @args;

  my $p = shift;
  if ( ref $p eq 'ARRAY' ) {
    # First argument might have been a hash reference
    @args = @{ ref $p->[0] ? [ %{ $p->[0] } ] : $p  };

  my $pv_spec;
  if(ref($_[0]) && ref($_[0]) =~ /HASH/) {
    $pv_spec = shift;
  my @coderefs = @_;

  my %rval = @args;
  # P::V::validate may alter it by applying defaults
  %rval = Params::Validate::validate(@args, $pv_spec) if($pv_spec);

  foreach (@coderefs) {
    die 'code-ref checking failed: arguments were not ' . document($_) . "\n"
        unless $_->({@args});

  return wantarray ? %rval : \%rval;

=head2 validate_with

Overrides and extends Params::Validate's function of the same name.

The code-ref, or an array-ref of code-refs, are passed as the
extra 'dependencies' argument.


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

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

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

  foreach (@{$coderefs}) {
    die('code-ref checking failed: arguments were not '.document($_)."\n") unless($_->({@{$params}}));

  return wantarray ? %rval : \%rval;

=head2 exclusively

Takes a single subref as its only argument (this would normally be the
results of one of the *_of functions), and returns a code-ref which
returns true if the hashref it is given only contains fields
mentioned in the original function or any of its children. For example

          qw(alpha beta gamma),
          all_of(qw(bar baz)),

will not tolerate arguments such as:

  bar   => ...,
  baz   => ...,
  sheep => ...

because sheep aren't mentioned in the 'any_of' and 'all_of's. Internally
this uses the auto-documenter interface to interrogate the child sub. This
means that if you want to use C<exclusively()> with third-party extensions
then they must support auto-documentation.

This function is not exported by default but can be.


sub exclusively {
  my @options = @_;
  my $childsub = shift;
    sub {
      my $documentation = document($childsub);
      if($Params::Validate::Dependencies::DOC) {
        return "exclusively ($documentation)";

      my @strings = map {
        s/\\'/'/g; $_
      } $documentation =~ /

      my %params = %{shift()};
      foreach my $param (keys %params) {
          return 0 if(!grep { $param eq $_ } @strings);
      return 1;

=head2 none_of

Returns a code-ref which checks that the hashref it receives matches
none of the options given.

You might want to use it thus:

    none_of(qw(bar baz))

to validate that 'alpha' must *not* be accompanied by 'bar' or 'baz'.


sub none_of {
  my @options = @_;
  _bless_right_class(_mk_autodoc(sub { _count_of(\@options, 0)->(@_) }));

=head2 one_of

Returns a code-ref which checks that the hashref it receives matches
only one of the options given.


sub one_of {
  my @options = @_;
  _bless_right_class(_mk_autodoc(sub { _count_of(\@options, 1)->(@_) }));

=head2 any_of

Returns a code-ref which checks that the hashref it receives matches
one or more of the options given.


sub any_of {
  my @options = @_;
  _bless_right_class(_mk_autodoc(sub {
    my %params = %{shift()};
    foreach my $option (@options) {
      return 1 if(!ref($option) && exists($params{$option}));
      return 1 if(ref($option) && $option->(\%params));
    return 0;

=head2 all_of

Returns a code-ref which checks that the hashref it receives matches
all of the options given.


sub all_of {
  my @options = @_;

  _bless_right_class(_mk_autodoc(sub { _count_of(\@options, $#options + 1)->(@_) }));

# {none,one,all}_of are thin wrappers around this
sub _count_of {
  my @options = @{shift()};
  my $desired_count = shift;
  sub {
    my %params = %{shift()};
    my $matches = 0;
    foreach my $option (@options) {
      $matches++ if(
        (!ref($option) && exists($params{$option})) ||
        (ref($option) && $option->(\%params))
    return ($matches == $desired_count);

sub _mk_autodoc {
  my $sub = shift;
  sub {
    if($DOC) {
      return $DOC->_doc_me(list => (closed_over($sub))[0]->{'@options'});

sub _bless_right_class {
  my($sub, $class) = (shift(), (caller(1))[3]);
  (my $subname = $class) =~ s/.*:://;
  no strict 'refs';
  unless(@{"${class}::ISA"}) {
    @{"${class}::ISA"} = ('Params::Validate::Dependencies::Documenter');
    *{"${class}::name"} = sub { $subname };
    *{"${class}::join_with"} = sub { $subname eq 'all_of' ? 'and' : 'or' };
  bless $sub, $class;

sub _validate_factory_args {
  my @options = @_;
  my $sub = (caller(1))[3];
  die("$sub takes only SCALARs, code-refs, and Params::Validate::Dependencies::* objects\n")
    if(grep {
      ref($_) && ref($_) !~ /CODE/ && 
      !(blessed($_) && $_->isa('Params::Validate::Dependencies::Documenter'))
    } @options);

=head1 LIES

Some of the above is incorrect.  If you really want to know what's
going on, look at L<Params::Validate::Dependencies::Extending>.


I like to know who's using my code.  All comments, including constructive
criticism, are welcome.

Please report any bugs either by email or
at L<>.

Any incompatibility with Params::Validate will be considered to be a bug,
with the exception of minor differences in error messages.

Bug reports should contain enough detail that I can replicate the
problem and write a test.  The best bug reports have those details
in the form of a .t file.  If you also include a patch I will love
you for ever.

=head1 SEE ALSO







Copyright 2016 David Cantrell E<lt>F<>E<gt>

This software is free-as-in-speech software, and may be used, distributed, and modified under the terms of either the GNU General Public Licence version 2 or the Artistic Licence. It's up to you which one you use. The full text of the licences can be found in the files GPL2.txt and ARTISTIC.txt, respectively.


This module is also free-as-in-mason.