5 use Carp qw[carp croak];
6 use Locale::Maketext::Simple Style => 'gettext';
12 use vars qw[ @ISA $VERSION @EXPORT_OK $VERBOSE $ALLOW_UNKNOWN
13 $STRICT_TYPE $STRIP_LEADING_DASHES $NO_DUPLICATES
14 $PRESERVE_CASE $ONLY_ALLOW_DEFINED $WARNINGS_FATAL
15 $SANITY_CHECK_TEMPLATE $CALLER_DEPTH $_ERROR_STRING
18 @ISA = qw[ Exporter ];
19 @EXPORT_OK = qw[check allow last_error];
22 $VERBOSE = $^W ? 1 : 0;
24 $STRIP_LEADING_DASHES = 0;
28 $ONLY_ALLOW_DEFINED = 0;
29 $SANITY_CHECK_TEMPLATE = 1;
34 my %known_keys = map { $_ => 1 }
35 qw| required allow default strict_type no_override
42 Params::Check - A generic input parsing/checking mechanism.
46 use Params::Check qw[check allow last_error];
48 sub fill_personal_info {
53 firstname => { required => 1, defined => 1 },
54 lastname => { required => 1, store => \$x },
55 gender => { required => 1,
56 allow => [qr/M/i, qr/F/i],
58 married => { allow => [0,1] },
59 age => { default => 21,
63 phone => { allow => [ sub { return 1 if /$valid_re/ },
66 id_list => { default => [],
69 employer => { default => 'NSA', no_override => 1 },
72 ### check() returns a hashref of parsed args on success ###
73 my $parsed_args = check( $tmpl, \%hash, $VERBOSE )
74 or die qw[Could not parse arguments!];
76 ... other code here ...
79 my $ok = allow( $colour, [qw|blue green yellow|] );
81 my $error = Params::Check::last_error();
86 Params::Check is a generic input parsing/checking mechanism.
88 It allows you to validate input via a template. The only requirement
89 is that the arguments must be named.
91 Params::Check can do the following things for you:
97 Convert all keys to lowercase
101 Check if all required arguments have been provided
105 Set arguments that have not been provided to the default
109 Weed out arguments that are not supported and warn about them to the
114 Validate the arguments given by the user based on strings, regexes,
115 lists or even subroutines
119 Enforce type integrity if required
123 Most of Params::Check's power comes from its template, which we'll
128 As you can see in the synopsis, based on your template, the arguments
129 provided will be validated.
131 The template can take a different set of rules per key that is used.
133 The following rules are available:
139 This is the default value if none was provided by the user.
140 This is also the type C<strict_type> will look at when checking type
141 integrity (see below).
145 A boolean flag that indicates if this argument was a required
146 argument. If marked as required and not provided, check() will fail.
150 This does a C<ref()> check on the argument provided. The C<ref> of the
151 argument must be the same as the C<ref> of the default value for this
154 This is very useful if you insist on taking an array reference as
155 argument for example.
159 If this template key is true, enforces that if this key is provided by
160 user input, its value is C<defined>. This just means that the user is
161 not allowed to pass C<undef> as a value for this key and is equivalent
163 allow => sub { defined $_[0] && OTHER TESTS }
167 This allows you to specify C<constants> in your template. ie, they
168 keys that are not allowed to be altered by the user. It pretty much
169 allows you to keep all your C<configurable> data in one place; the
170 C<Params::Check> template.
174 This allows you to pass a reference to a scalar, in which the data
178 my $args = check(foo => { default => 1, store => \$x }, $input);
180 This is basically shorthand for saying:
182 my $args = check( { foo => { default => 1 }, $input );
183 my $x = $args->{foo};
185 You can alter the global variable $Params::Check::NO_DUPLICATES to
186 control whether the C<store>'d key will still be present in your
187 result set. See the L<Global Variables> section below.
191 A set of criteria used to validate a particular piece of data if it
192 has to adhere to particular rules.
194 See the C<allow()> function for details.
200 =head2 check( \%tmpl, \%args, [$verbose] );
202 This function is not exported by default, so you'll have to ask for it
205 use Params::Check qw[check];
207 or use its fully qualified name instead.
209 C<check> takes a list of arguments, as follows:
215 This is a hashreference which contains a template as explained in the
216 C<SYNOPSIS> and C<Template> section.
220 This is a reference to a hash of named arguments which need checking.
224 A boolean to indicate whether C<check> should be verbose and warn
225 about what went wrong in a check or not.
227 You can enable this program wide by setting the package variable
228 C<$Params::Check::VERBOSE> to a true value. For details, see the
229 section on C<Global Variables> below.
233 C<check> will return when it fails, or a hashref with lowercase
234 keys of parsed arguments when it succeeds.
236 So a typical call to check would look like this:
238 my $parsed = check( \%template, \%arguments, $VERBOSE )
239 or warn q[Arguments could not be parsed!];
241 A lot of the behaviour of C<check()> can be altered by setting
242 package variables. See the section on C<Global Variables> for details
248 my ($utmpl, $href, $verbose) = @_;
250 ### did we get the arguments we need? ###
251 return if !$utmpl or !$href;
253 ### sensible defaults ###
254 $verbose ||= $VERBOSE || 0;
256 ### clear the current error string ###
259 ### XXX what type of template is it? ###
261 #if (ref $args eq 'HASH') {
265 ### clean up the template ###
266 my $args = _clean_up_args( $href ) or return;
268 ### sanity check + defaults + required keys set? ###
269 my $defs = _sanity_check_and_defaults( $utmpl, $args, $verbose )
272 ### deref only once ###
277 ### flag to see if anything went wrong ###
280 ### flag to see if we warned for anything, needed for warnings_fatal
283 for my $key (keys %args) {
285 ### you gave us this key, but it's not in the template ###
286 unless( $utmpl{$key} ) {
288 ### but we'll allow it anyway ###
289 if( $ALLOW_UNKNOWN ) {
290 $defs{$key} = $args{$key};
292 ### warn about the error ###
295 loc("Key '%1' is not a valid key for %2 provided by %3",
296 $key, _who_was_it(), _who_was_it(1)), $verbose);
302 ### check if you're even allowed to override this key ###
303 if( $utmpl{$key}->{'no_override'} ) {
305 loc(q[You are not allowed to override key '%1'].
306 q[for %2 from %3], $key, _who_was_it(), _who_was_it(1)),
313 ### copy of this keys template instructions, to save derefs ###
314 my %tmpl = %{$utmpl{$key}};
316 ### check if you were supposed to provide defined() values ###
317 if( ($tmpl{'defined'} || $ONLY_ALLOW_DEFINED) and
318 not defined $args{$key}
320 _store_error(loc(q|Key '%1' must be defined when passed|, $key),
326 ### check if they should be of a strict type, and if it is ###
327 if( ($tmpl{'strict_type'} || $STRICT_TYPE) and
328 (ref $args{$key} ne ref $tmpl{'default'})
330 _store_error(loc(q|Key '%1' needs to be of type '%2'|,
331 $key, ref $tmpl{'default'} || 'SCALAR'), $verbose );
336 ### check if we have an allow handler, to validate against ###
337 ### allow() will report its own errors ###
338 if( exists $tmpl{'allow'} and not do {
339 local $_ERROR_STRING;
340 allow( $args{$key}, $tmpl{'allow'} )
343 ### stringify the value in the error report -- we don't want dumps
344 ### of objects, but we do want to see *roughly* what we passed
345 _store_error(loc(q|Key '%1' (%2) is of invalid type for '%3' |.
347 $key, "$args{$key}", _who_was_it(),
348 _who_was_it(1)), $verbose);
353 ### we got here, then all must be OK ###
354 $defs{$key} = $args{$key};
358 ### croak with the collected errors if there were errors and
359 ### we have the fatal flag toggled.
360 croak(__PACKAGE__->last_error) if ($wrong || $warned) && $WARNINGS_FATAL;
362 ### done with our loop... if $wrong is set, something went wrong
363 ### and the user is already informed, just return...
366 ### check if we need to store any of the keys ###
367 ### can't do it before, because something may go wrong later,
368 ### leaving the user with a few set variables
369 for my $key (keys %defs) {
370 if( my $ref = $utmpl{$key}->{'store'} ) {
371 $$ref = $NO_DUPLICATES ? delete $defs{$key} : $defs{$key};
378 =head2 allow( $test_me, \@criteria );
380 The function that handles the C<allow> key in the template is also
381 available for independent use.
383 The function takes as first argument a key to test against, and
384 as second argument any form of criteria that are also allowed by
385 the C<allow> key in the template.
387 You can use the following types of values for allow:
393 The provided argument MUST be equal to the string for the validation
398 The provided argument MUST match the regular expression for the
403 The provided subroutine MUST return true in order for the validation
404 to pass and the argument accepted.
406 (This is particularly useful for more complicated data).
410 The provided argument MUST equal one of the elements of the array
411 ref for the validation to pass. An array ref can hold all the above
416 It returns true if the key matched the criteria, or false otherwise.
421 ### use $_[0] and $_[1] since this is hot code... ###
422 #my ($val, $ref) = @_;
424 ### it's a regexp ###
425 if( ref $_[1] eq 'Regexp' ) {
426 local $^W; # silence warnings if $val is undef #
427 return if $_[0] !~ /$_[1]/;
430 } elsif ( ref $_[1] eq 'CODE' ) {
431 return unless $_[1]->( $_[0] );
433 ### it's an array ###
434 } elsif ( ref $_[1] eq 'ARRAY' ) {
436 ### loop over the elements, see if one of them says the
438 ### also, short-circuit when possible
440 return 1 if allow( $_[0], $_ );
445 ### fall back to a simple, but safe 'eq' ###
447 return unless _safe_eq( $_[0], $_[1] );
450 ### we got here, no failures ###
454 ### helper functions ###
456 ### clean up the template ###
458 ### don't even bother to loop, if there's nothing to clean up ###
459 return $_[0] if $PRESERVE_CASE and !$STRIP_LEADING_DASHES;
463 ### keys are note aliased ###
464 for my $key (keys %args) {
466 $key = lc $key unless $PRESERVE_CASE;
467 $key =~ s/^-// if $STRIP_LEADING_DASHES;
468 $args{$key} = delete $args{$org} if $key ne $org;
471 ### return references so we always return 'true', even on empty
476 sub _sanity_check_and_defaults {
477 my %utmpl = %{$_[0]};
482 for my $key (keys %utmpl) {
484 ### check if required keys are provided
485 ### keys are now lower cased, unless preserve case was enabled
486 ### at which point, the utmpl keys must match, but that's the users
488 if( $utmpl{$key}->{'required'} and not exists $args{$key} ) {
490 loc(q|Required option '%1' is not provided for %2 by %3|,
491 $key, _who_was_it(1), _who_was_it(2)), $verbose );
493 ### mark the error ###
498 ### next, set the default, make sure the key exists in %defs ###
499 $defs{$key} = $utmpl{$key}->{'default'}
500 if exists $utmpl{$key}->{'default'};
502 if( $SANITY_CHECK_TEMPLATE ) {
503 ### last, check if they provided any weird template keys
504 ### -- do this last so we don't always execute this code.
505 ### just a small optimization.
507 loc(q|Template type '%1' not supported [at key '%2']|,
511 } keys %{$utmpl{$key}};
513 ### make sure you passed a ref, otherwise, complain about it!
514 if ( exists $utmpl{$key}->{'store'} ) {
516 q|Store variable for '%1' is not a reference!|, $key
517 ), 1, 1 ) unless ref $utmpl{$key}->{'store'};
525 ### return references so we always return 'true', even on empty
531 ### only do a straight 'eq' if they're both defined ###
532 return defined($_[0]) && defined($_[1])
534 : defined($_[0]) eq defined($_[1]);
538 my $level = $_[0] || 0;
540 return (caller(2 + $CALLER_DEPTH + $level))[3] || 'ANON'
545 Returns a string containing all warnings and errors reported during
546 the last time C<check> was called.
548 This is useful if you want to report then some other way than
549 C<carp>'ing when the verbose flag is on.
551 It is exported upon request.
555 { $_ERROR_STRING = '';
558 my($err, $verbose, $offset) = @_[0..2];
561 my $level = 1 + $offset;
563 local $Carp::CarpLevel = $level;
565 carp $err if $verbose;
567 $_ERROR_STRING .= $err . "\n";
574 sub last_error { $_ERROR_STRING }
579 =head1 Global Variables
581 The behaviour of Params::Check can be altered by changing the
582 following global variables:
584 =head2 $Params::Check::VERBOSE
586 This controls whether Params::Check will issue warnings and
587 explanations as to why certain things may have failed.
588 If you set it to 0, Params::Check will not output any warnings.
590 The default is 1 when L<warnings> are enabled, 0 otherwise;
592 =head2 $Params::Check::STRICT_TYPE
594 This works like the C<strict_type> option you can pass to C<check>,
595 which will turn on C<strict_type> globally for all calls to C<check>.
599 =head2 $Params::Check::ALLOW_UNKNOWN
601 If you set this flag, unknown options will still be present in the
602 return value, rather than filtered out. This is useful if your
603 subroutine is only interested in a few arguments, and wants to pass
604 the rest on blindly to perhaps another subroutine.
608 =head2 $Params::Check::STRIP_LEADING_DASHES
610 If you set this flag, all keys passed in the following manner:
612 function( -key => 'val' );
614 will have their leading dashes stripped.
616 =head2 $Params::Check::NO_DUPLICATES
618 If set to true, all keys in the template that are marked as to be
619 stored in a scalar, will also be removed from the result set.
621 Default is false, meaning that when you use C<store> as a template
622 key, C<check> will put it both in the scalar you supplied, as well as
623 in the hashref it returns.
625 =head2 $Params::Check::PRESERVE_CASE
627 If set to true, L<Params::Check> will no longer convert all keys from
628 the user input to lowercase, but instead expect them to be in the
629 case the template provided. This is useful when you want to use
630 similar keys with different casing in your templates.
632 Understand that this removes the case-insensitivity feature of this
637 =head2 $Params::Check::ONLY_ALLOW_DEFINED
639 If set to true, L<Params::Check> will require all values passed to be
640 C<defined>. If you wish to enable this on a 'per key' basis, use the
641 template option C<defined> instead.
645 =head2 $Params::Check::SANITY_CHECK_TEMPLATE
647 If set to true, L<Params::Check> will sanity check templates, validating
648 for errors and unknown keys. Although very useful for debugging, this
649 can be somewhat slow in hot-code and large loops.
651 To disable this check, set this variable to C<false>.
655 =head2 $Params::Check::WARNINGS_FATAL
657 If set to true, L<Params::Check> will C<croak> when an error during
658 template validation occurs, rather than return C<false>.
662 =head2 $Params::Check::CALLER_DEPTH
664 This global modifies the argument given to C<caller()> by
665 C<Params::Check::check()> and is useful if you have a custom wrapper
666 function around C<Params::Check::check()>. The value must be an
667 integer, indicating the number of wrapper functions inserted between
668 the real function call and C<Params::Check::check()>.
670 Example wrapper function, using a custom stacktrace:
673 my ($template, $args_in) = @_;
675 local $Params::Check::WARNINGS_FATAL = 1;
676 local $Params::Check::CALLER_DEPTH = $Params::Check::CALLER_DEPTH + 1;
677 my $args_out = Params::Check::check($template, $args_in);
679 my_stacktrace(Params::Check::last_error) unless $args_out;
689 Jos Boumans E<lt>kane@cpan.orgE<gt>.
691 =head1 Acknowledgements
693 Thanks to Richard Soderberg for his performance improvements.
698 copyright (c) 2003,2004 Jos Boumans E<lt>kane@cpan.orgE<gt>.
701 This library is free software;
702 you may redistribute and/or modify it under the same
703 terms as Perl itself.
708 # c-indentation-style: bsd
710 # indent-tabs-mode: nil
712 # vim: expandtab shiftwidth=4: