blib/lib/Params/Validate/PP.pm untested

filter: Statementstmt 0.0% 0 / 288 Branchbran 0.0% 0 / 200 Conditioncond 0.0% 0 / 92 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 615 CC 101 SCAR 59.9
CC
101
Cov
0%
validate
812.0
_validate_one_param
650.0
validate_pos
420.0
CRAP 399.4
1 package Params::Validate::PP;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = '1.29';
7  
8 use Params::Validate::Constants;
9 use Scalar::Util 1.10 ();
10  
11 our $options;
12  
13 # Various internals notes (for me and any future readers of this
14 # monstrosity):
15 #
16 # - A lot of the weirdness is _intentional_, because it optimizes for
17 # the _success_ case. It does not really matter how slow the code is
18 # after it enters a path that leads to reporting failure. But the
19 # "success" path should be as fast as possible.
20 #
21 # -- We only calculate $called as needed for this reason, even though it
22 # means copying code all over.
23 #
24 # - All the validation routines need to be careful never to alter the
25 # references that are passed.
26 #
27 # -- The code assumes that _most_ callers will not be using the
28 # skip_leading or ignore_case features. In order to not alter the
29 # references passed in, we copy them wholesale when normalizing them
30 # to make these features work. This is slower but lets us be faster
31 # when not using them.
32  
33 # Matt Sergeant came up with this prototype, which slickly takes the
34 # first array (which should be the caller's @_), and makes it a
35 # reference. Everything after is the parameters for validation.
36 sub validate_pos (\@@) {
37 return if $Params::Validate::NO_VALIDATION && !defined wantarray;
38  
39 my $p = shift;
40  
41 my @specs = @_;
42  
43 my @p = @$p;
44 if ($Params::Validate::NO_VALIDATION) {
45  
46 # if the spec is bigger that's where we can start adding
47 # defaults
48 for ( my $x = $#p + 1; $x <= $#specs; $x++ ) {
49 $p[$x] = $specs[$x]->{default}
50 if ref $specs[$x] && exists $specs[$x]->{default};
51 }
52  
53 return wantarray ? @p : \@p;
54 }
55  
56 # I'm too lazy to pass these around all over the place.
57 local $options ||= _get_options( ( caller(0) )[0] )
58 unless defined $options;
59  
60 my $min = 0;
61  
62 while (1) {
63 last
64 unless (
65 ref $specs[$min]
66 ? !( exists $specs[$min]->{default} || $specs[$min]->{optional} )
67 : $specs[$min]
68 );
69  
70 $min++;
71 }
72  
73 my $max = scalar @specs;
74  
75 my $actual = scalar @p;
76 unless ( $actual >= $min
77 && ( $options->{allow_extra} || $actual <= $max ) ) {
78 my $minmax = (
79 $options->{allow_extra}
80 ? "at least $min"
81 : ( $min != $max ? "$min - $max" : $max )
82 );
83  
84 my $val = $options->{allow_extra} ? $min : $max;
85 $minmax .= $val != 1 ? ' were' : ' was';
86  
87 my $called = _get_called();
88  
89 $options->{on_fail}->( "$actual parameter"
90 . ( $actual != 1 ? 's' : '' ) . " "
91 . ( $actual != 1 ? 'were' : 'was' )
92 . " passed to $called but $minmax expected\n" );
93 }
94  
95 my $bigger = $#p > $#specs ? $#p : $#specs;
96 foreach ( 0 .. $bigger ) {
97 my $spec = $specs[$_];
98  
99 next unless ref $spec;
100  
101 if ( $_ <= $#p ) {
102 _validate_one_param(
103 $p[$_], \@p, $spec,
104 'Parameter #' . ( $_ + 1 ) . ' (%s)'
105 );
106 }
107  
108 $p[$_] = $spec->{default} if $_ > $#p && exists $spec->{default};
109 }
110  
111 _validate_pos_depends( \@p, \@specs );
112  
113 foreach (
114 grep {
115 defined $p[$_]
116 && !ref $p[$_]
117 && ref $specs[$_]
118 && $specs[$_]{untaint}
119 } 0 .. $bigger
120 ) {
121 ( $p[$_] ) = $p[$_] =~ /(.+)/;
122 }
123  
124 return wantarray ? @p : \@p;
125 }
126  
127 sub _validate_pos_depends {
128 my ( $p, $specs ) = @_;
129  
130 for my $p_idx ( 0 .. $#$p ) {
131 my $spec = $specs->[$p_idx];
132  
133 next
134 unless $spec
135 && UNIVERSAL::isa( $spec, 'HASH' )
136 && exists $spec->{depends};
137  
138 my $depends = $spec->{depends};
139  
140 if ( ref $depends ) {
141 require Carp;
142 local $Carp::CarpLevel = 2;
143 Carp::croak(
144 "Arguments to 'depends' for validate_pos() must be a scalar");
145 }
146  
147 my $p_size = scalar @$p;
148 if ( $p_size < $depends - 1 ) {
149 my $error
150 = ( "Parameter #"
151 . ( $p_idx + 1 )
152 . " depends on parameter #"
153 . $depends
154 . ", which was not given" );
155  
156 $options->{on_fail}->($error);
157 }
158 }
159 return 1;
160 }
161  
162 sub _validate_named_depends {
163 my ( $p, $specs ) = @_;
164  
165 foreach my $pname ( keys %$p ) {
166 my $spec = $specs->{$pname};
167  
168 next
169 unless $spec
170 && UNIVERSAL::isa( $spec, 'HASH' )
171 && $spec->{depends};
172  
173 unless ( UNIVERSAL::isa( $spec->{depends}, 'ARRAY' )
174 || !ref $spec->{depends} ) {
175 require Carp;
176 local $Carp::CarpLevel = 2;
177 Carp::croak(
178 "Arguments to 'depends' must be a scalar or arrayref");
179 }
180  
181 foreach my $depends_name (
182 ref $spec->{depends}
183 ? @{ $spec->{depends} }
184 : $spec->{depends}
185 ) {
186 unless ( exists $p->{$depends_name} ) {
187 my $error
188 = ( "Parameter '$pname' depends on parameter '"
189 . $depends_name
190 . "', which was not given" );
191  
192 $options->{on_fail}->($error);
193 }
194 }
195 }
196 }
197  
198 sub validate (\@$) {
199 return if $Params::Validate::NO_VALIDATION && !defined wantarray;
200  
201 my $p = $_[0];
202  
203 my $specs = $_[1];
204 local $options = _get_options( ( caller(0) )[0] ) unless defined $options;
205  
206 if ( ref $p eq 'ARRAY' ) {
207  
208 # we were called as validate( @_, ... ) where @_ has a
209 # single element, a hash reference
210 if ( ref $p->[0] ) {
211 $p = { %{ $p->[0] } };
212 }
213 elsif ( @$p % 2 ) {
214 my $called = _get_called();
215  
216 $options->{on_fail}
217 ->( "Odd number of parameters in call to $called "
218 . "when named parameters were expected\n" );
219 }
220 else {
221 $p = {@$p};
222 }
223 }
224  
225 if ( $options->{normalize_keys} ) {
226 $specs = _normalize_callback( $specs, $options->{normalize_keys} );
227 $p = _normalize_callback( $p, $options->{normalize_keys} );
228 }
229 elsif ( $options->{ignore_case} || $options->{strip_leading} ) {
230 $specs = _normalize_named($specs);
231 $p = _normalize_named($p);
232 }
233  
234 if ($Params::Validate::NO_VALIDATION) {
235 return (
236 wantarray
237 ? (
238  
239 # this is a hash containing just the defaults
240 (
241 map { $_ => $specs->{$_}->{default} }
242 grep {
243 ref $specs->{$_}
244 && exists $specs->{$_}->{default}
245 }
246 keys %$specs
247 ),
248 (
249 ref $p eq 'ARRAY'
250 ? (
251 ref $p->[0]
252 ? %{ $p->[0] }
253 : @$p
254 )
255 : %$p
256 )
257 )
258 : do {
259 my $ref = (
260 ref $p eq 'ARRAY'
261 ? (
262 ref $p->[0]
263 ? $p->[0]
264 : {@$p}
265 )
266 : $p
267 );
268  
269 foreach (
270 grep {
271 ref $specs->{$_}
272 && exists $specs->{$_}->{default}
273 }
274 keys %$specs
275 ) {
276 $ref->{$_} = $specs->{$_}->{default}
277 unless exists $ref->{$_};
278 }
279  
280 return $ref;
281 }
282 );
283 }
284  
285 _validate_named_depends( $p, $specs );
286  
287 unless ( $options->{allow_extra} ) {
288 if ( my @unmentioned = grep { !exists $specs->{$_} } keys %$p ) {
289 my $called = _get_called();
290  
291 $options->{on_fail}->( "The following parameter"
292 . ( @unmentioned > 1 ? 's were' : ' was' )
293 . " passed in the call to $called but "
294 . ( @unmentioned > 1 ? 'were' : 'was' )
295 . " not listed in the validation options: @unmentioned\n"
296 );
297 }
298 }
299  
300 my @missing;
301  
302 # the iterator needs to be reset in case the same hashref is being
303 # passed to validate() on successive calls, because we may not go
304 # through all the hash's elements
305 keys %$specs;
306 OUTER:
307 while ( my ( $key, $spec ) = each %$specs ) {
308 if (
309 !exists $p->{$key}
310 && (
311 ref $spec
312 ? !(
313 do {
314  
315 # we want to short circuit the loop here if we
316 # can assign a default, because there's no need
317 # check anything else at all.
318 if ( exists $spec->{default} ) {
319 $p->{$key} = $spec->{default};
320 next OUTER;
321 }
322 }
323 || do {
324  
325 # Similarly, an optional parameter that is
326 # missing needs no additional processing.
327 next OUTER if $spec->{optional};
328 }
329 )
330 : $spec
331 )
332 ) {
333 push @missing, $key;
334 }
335  
336 # Can't validate a non hashref spec beyond the presence or
337 # absence of the parameter.
338 elsif ( ref $spec ) {
339 my $value = defined $p->{$key} ? qq|"$p->{$key}"| : 'undef';
340 _validate_one_param(
341 $p->{$key}, $p, $spec,
342 qq{The '$key' parameter (%s)}
343 );
344 }
345 }
346  
347 if (@missing) {
348 my $called = _get_called();
349  
350 my $missing = join ', ', map {"'$_'"} sort @missing;
351 $options->{on_fail}->( "Mandatory parameter"
352 . ( @missing > 1 ? 's' : '' )
353 . " $missing missing in call to $called\n" );
354 }
355  
356 # do untainting after we know everything passed
357 foreach my $key (
358 grep {
359 defined $p->{$_}
360 && !ref $p->{$_}
361 && ref $specs->{$_}
362 && $specs->{$_}{untaint}
363 }
364 keys %$p
365 ) {
366 ( $p->{$key} ) = $p->{$key} =~ /(.+)/;
367 }
368  
369 return wantarray ? %$p : $p;
370 }
371  
372 sub validate_with {
373 return if $Params::Validate::NO_VALIDATION && !defined wantarray;
374  
375 my %p = @_;
376  
377 local $options = _get_options( ( caller(0) )[0], %p );
378  
379 unless ($Params::Validate::NO_VALIDATION) {
380 unless ( exists $options->{called} ) {
381 $options->{called} = ( caller( $options->{stack_skip} ) )[3];
382 }
383  
384 }
385  
386 if ( UNIVERSAL::isa( $p{spec}, 'ARRAY' ) ) {
387 return validate_pos( @{ $p{params} }, @{ $p{spec} } );
388 }
389 else {
390  
391 # intentionally ignore the prototype because this contains
392 # either an array or hash reference, and validate() will
393 # handle either one properly
394 return &validate( $p{params}, $p{spec} );
395 }
396 }
397  
398 sub _normalize_callback {
399 my ( $p, $func ) = @_;
400  
401 my %new;
402  
403 foreach my $key ( keys %$p ) {
404 my $new_key = $func->($key);
405  
406 unless ( defined $new_key ) {
407 die
408 "The normalize_keys callback did not return a defined value when normalizing the key '$key'";
409 }
410  
411 if ( exists $new{$new_key} ) {
412 die
413 "The normalize_keys callback returned a key that already exists, '$new_key', when normalizing the key '$key'";
414 }
415  
416 $new{$new_key} = $p->{$key};
417 }
418  
419 return \%new;
420 }
421  
422 sub _normalize_named {
423  
424 # intentional copy so we don't destroy original
425 my %h = ( ref $_[0] ) =~ /ARRAY/ ? @{ $_[0] } : %{ $_[0] };
426  
427 if ( $options->{ignore_case} ) {
428 $h{ lc $_ } = delete $h{$_} for keys %h;
429 }
430  
431 if ( $options->{strip_leading} ) {
432 foreach my $key ( keys %h ) {
433 my $new;
434 ( $new = $key ) =~ s/^\Q$options->{strip_leading}\E//;
435 $h{$new} = delete $h{$key};
436 }
437 }
438  
439 return \%h;
440 }
441  
442 my %Valid = map { $_ => 1 }
443 qw( callbacks can default depends isa optional regex type untaint );
444  
445 sub _validate_one_param {
446 my ( $value, $params, $spec, $id ) = @_;
447  
448 # for my $key ( keys %{$spec} ) {
449 # unless ( $Valid{$key} ) {
450 # $options->{on_fail}
451 # ->(qq{"$key" is not an allowed validation spec key});
452 # }
453 # }
454  
455 if ( exists $spec->{type} ) {
456 unless ( defined $spec->{type}
457 && Scalar::Util::looks_like_number( $spec->{type} )
458 && $spec->{type} > 0 ) {
459 my $msg
460 = "$id has a type specification which is not a number. It is ";
461 if ( defined $spec->{type} ) {
462 $msg .= "a string - $spec->{type}";
463 }
464 else {
465 $msg .= "undef";
466 }
467  
468 $msg
469 .= ".\n Use the constants exported by Params::Validate to declare types.";
470  
471 $options->{on_fail}->( sprintf( $msg, _stringify($value) ) );
472 }
473  
474 unless ( _get_type($value) & $spec->{type} ) {
475 my $type = _get_type($value);
476  
477 my @is = _typemask_to_strings($type);
478 my @allowed = _typemask_to_strings( $spec->{type} );
479 my $article = $is[0] =~ /^[aeiou]/i ? 'an' : 'a';
480  
481 my $called = _get_called(1);
482  
483 $options->{on_fail}->(
484 sprintf(
485 "$id to $called was $article '@is', which "
486 . "is not one of the allowed types: @allowed\n",
487 _stringify($value)
488 )
489 );
490 }
491 }
492  
493 # short-circuit for common case
494 return
495 unless ( $spec->{isa}
496 || $spec->{can}
497 || $spec->{callbacks}
498 || $spec->{regex} );
499  
500 if ( exists $spec->{isa} ) {
501 foreach ( ref $spec->{isa} ? @{ $spec->{isa} } : $spec->{isa} ) {
502 unless (
503 do {
504 local $@ = q{};
505 eval { $value->isa($_) };
506 }
507 ) {
508 my $is = ref $value ? ref $value : 'plain scalar';
509 my $article1 = $_ =~ /^[aeiou]/i ? 'an' : 'a';
510 my $article2 = $is =~ /^[aeiou]/i ? 'an' : 'a';
511  
512 my $called = _get_called(1);
513  
514 $options->{on_fail}->(
515 sprintf(
516 "$id to $called was not $article1 '$_' "
517 . "(it is $article2 $is)\n", _stringify($value)
518 )
519 );
520 }
521 }
522 }
523  
524 if ( exists $spec->{can} ) {
525 foreach ( ref $spec->{can} ? @{ $spec->{can} } : $spec->{can} ) {
526 unless (
527 do {
528 local $@ = q{};
529 eval { $value->can($_) };
530 }
531 ) {
532 my $called = _get_called(1);
533  
534 $options->{on_fail}->(
535 sprintf(
536 "$id to $called does not have the method: '$_'\n",
537 _stringify($value)
538 )
539 );
540 }
541 }
542 }
543  
544 if ( $spec->{callbacks} ) {
545 unless ( UNIVERSAL::isa( $spec->{callbacks}, 'HASH' ) ) {
546 my $called = _get_called(1);
547  
548 $options->{on_fail}->(
549 "'callbacks' validation parameter for $called must be a hash reference\n"
550 );
551 }
552  
553 foreach ( keys %{ $spec->{callbacks} } ) {
554 unless ( UNIVERSAL::isa( $spec->{callbacks}{$_}, 'CODE' ) ) {
555 my $called = _get_called(1);
556  
557 $options->{on_fail}->(
558 "callback '$_' for $called is not a subroutine reference\n"
559 );
560 }
561  
562 my $ok;
563 my $e = do {
564 local $@ = q{};
565 local $SIG{__DIE__};
566 $ok = eval { $spec->{callbacks}{$_}->( $value, $params ) };
567 $@;
568 };
569  
570 if ( !$ok ) {
571 my $called = _get_called(1);
572  
573 if ( ref $e ) {
574 $options->{on_fail}->($e);
575 }
576 else {
577 my $msg = "$id to $called did not pass the '$_' callback";
578 $msg .= ": $e" if length $e;
579 $msg .= "\n";
580 $options->{on_fail}->( sprintf( $msg, _stringify($value) ) );
581 }
582 }
583 }
584 }
585  
586 if ( exists $spec->{regex} ) {
587 unless ( ( defined $value ? $value : '' ) =~ /$spec->{regex}/ ) {
588 my $called = _get_called(1);
589  
590 $options->{on_fail}->(
591 sprintf(
592 "$id to $called did not pass regex check\n",
593 _stringify($value)
594 )
595 );
596 }
597 }
598 }
599  
600 {
601 # if it UNIVERSAL::isa the string on the left then its the type on
602 # the right
603 my %isas = (
604 'ARRAY' => ARRAYREF,
605 'HASH' => HASHREF,
606 'CODE' => CODEREF,
607 'GLOB' => GLOBREF,
608 'SCALAR' => SCALARREF,
609 'REGEXP' => SCALARREF,
610 );
611 my %simple_refs = map { $_ => 1 } keys %isas;
612  
613 sub _get_type {
614 return UNDEF unless defined $_[0];
615  
616 my $ref = ref $_[0];
617 unless ($ref) {
618  
619 # catches things like: my $fh = do { local *FH; };
620 return GLOB if UNIVERSAL::isa( \$_[0], 'GLOB' );
621 return SCALAR;
622 }
623  
624 return $isas{$ref} if $simple_refs{$ref};
625  
626 foreach ( keys %isas ) {
627 return $isas{$_} | OBJECT if UNIVERSAL::isa( $_[0], $_ );
628 }
629  
630 # I really hope this never happens.
631 return UNKNOWN;
632 }
633 }
634  
635 {
636 my %type_to_string = (
637 SCALAR() => 'scalar',
638 ARRAYREF() => 'arrayref',
639 HASHREF() => 'hashref',
640 CODEREF() => 'coderef',
641 GLOB() => 'glob',
642 GLOBREF() => 'globref',
643 SCALARREF() => 'scalarref',
644 UNDEF() => 'undef',
645 OBJECT() => 'object',
646 UNKNOWN() => 'unknown',
647 );
648  
649 sub _typemask_to_strings {
650 my $mask = shift;
651  
652 my @types;
653 foreach (
654 SCALAR, ARRAYREF, HASHREF, CODEREF, GLOB, GLOBREF,
655 SCALARREF, UNDEF, OBJECT, UNKNOWN
656 ) {
657 push @types, $type_to_string{$_} if $mask & $_;
658 }
659 return @types ? @types : ('unknown');
660 }
661 }
662  
663 {
664 my %defaults = (
665 ignore_case => 0,
666 strip_leading => 0,
667 allow_extra => 0,
668 on_fail => sub {
669 require Carp;
670 Carp::croak( $_[0] );
671 },
672 stack_skip => 1,
673 normalize_keys => undef,
674 );
675  
676 *set_options = \&validation_options;
677  
678 sub validation_options {
679 my %opts = @_;
680  
681 my $caller = caller;
682  
683 foreach ( keys %defaults ) {
684 $opts{$_} = $defaults{$_} unless exists $opts{$_};
685 }
686  
687 $Params::Validate::OPTIONS{$caller} = \%opts;
688 }
689  
690 sub _get_options {
691 my $caller = shift;
692  
693 if (@_) {
694  
695 return (
696 $Params::Validate::OPTIONS{$caller}
697 ? {
698 %{ $Params::Validate::OPTIONS{$caller} },
699 @_
700 }
701 : { %defaults, @_ }
702 );
703 }
704 else {
705 return (
706 exists $Params::Validate::OPTIONS{$caller}
707 ? $Params::Validate::OPTIONS{$caller}
708 : \%defaults
709 );
710 }
711 }
712 }
713  
714 sub _get_called {
715 my $extra_skip = $_[0] || 0;
716  
717 # always add one more for this sub
718 $extra_skip++;
719  
720 my $called = (
721 exists $options->{called}
722 ? $options->{called}
723 : ( caller( $options->{stack_skip} + $extra_skip ) )[3]
724 );
725  
726 $called = '(unknown)' unless defined $called;
727  
728 return $called;
729 }
730  
731 sub _stringify {
732 return defined $_[0] ? qq{"$_[0]"} : 'undef';
733 }
734  
735 1;