-
Notifications
You must be signed in to change notification settings - Fork 3
/
Dependencies.pm
396 lines (297 loc) · 10.1 KB
/
Dependencies.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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);
use vars qw($VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS $DOC);
$VERSION = '2.00';
$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;
_validate_factory_args(@_);
$orig->(@_);
};
}
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
=head1 DESCRIPTION
Extends Params::Validate to make it easy to validate
that you have been passed the correct combinations of parameters.
=head1 SYNOPSIS
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 {
validate(@_,
{
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 },
},
any_of(
qw(alpha beta gamma),
all_of(qw(bar baz)),
)
);
}
=head1 HOW IT WORKS
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.
=head1 SUBROUTINES and EXPORTS
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.
=cut
sub document {
my $sub = shift;
die(__PACKAGE__."::document: object $sub is wrong type\n")
unless(blessed($sub) && $sub->can('_document'));
$sub->_document();
}
=head2 validate
Overrides and extends Params::Validate's function of the same name.
=cut
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.
=cut
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
...
validate(@_,
exclusively(
any_of(
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.
=cut
sub exclusively {
my @options = @_;
my $childsub = shift;
_bless_right_class(
sub {
my $documentation = document($childsub);
if($Params::Validate::Dependencies::DOC) {
return "exclusively ($documentation)";
}
my @strings = map {
s/\\'/'/g; $_
} $documentation =~ /
'
(
(?:\\'|[^'])+
)
'
/xg;
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:
all_of(
'alpha',
none_of(qw(bar baz))
)
to validate that 'alpha' must *not* be accompanied by 'bar' or 'baz'.
=cut
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.
=cut
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.
=cut
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.
=cut
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->(@_);
}
}
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>.
=head1 BUGS, LIMITATIONS, and FEEDBACK
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<https://github.com/DrHyde/perl-modules-Params-Validate-Dependencies/issues>.
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
L<Params::Validate>
L<Data::Domain>
=head1 SOURCE CODE REPOSITORY
L<git://github.com/DrHyde/perl-modules-Params-Validate-Dependencies.git>
L<https://github.com/DrHyde/perl-modules-Params-Validate-Dependencies/>
=head1 COPYRIGHT and LICENCE
Copyright 2023 David Cantrell E<lt>F<david@cantrell.org.uk>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.
=head1 CONSPIRACY
This module is also free-as-in-mason.
=cut
1;