Add built local::lib
[catagits/Gitalist.git] / local-lib5 / lib / perl5 / i486-linux-gnu-thread-multi / Params / Validate.pm
1 package Params::Validate;
2
3 use strict;
4
5 BEGIN {
6     use Exporter;
7     use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK
8         %EXPORT_TAGS %OPTIONS $options $NO_VALIDATION );
9
10     @ISA = 'Exporter';
11
12     $VERSION = '0.94';
13
14     my %tags = (
15         types => [
16             qw( SCALAR ARRAYREF HASHREF CODEREF GLOB GLOBREF
17                 SCALARREF HANDLE BOOLEAN UNDEF OBJECT )
18         ],
19     );
20
21     %EXPORT_TAGS = (
22         'all' => [
23             qw( validate validate_pos validation_options validate_with ),
24             map { @{ $tags{$_} } } keys %tags
25         ],
26         %tags,
27     );
28
29     @EXPORT_OK = ( @{ $EXPORT_TAGS{all} }, 'set_options' );
30     @EXPORT = qw( validate validate_pos );
31
32     $NO_VALIDATION = $ENV{PERL_NO_VALIDATION};
33
34     eval { require Params::ValidateXS; } unless $ENV{PV_TEST_PERL};
35
36     if ( $@ || $ENV{PV_TEST_PERL} ) {
37         require Params::ValidatePP;
38     }
39 }
40
41 1;
42
43 __END__
44
45 =head1 NAME
46
47 Params::Validate - Validate method/function parameters
48
49 =head1 SYNOPSIS
50
51   use Params::Validate qw(:all);
52
53   # takes named params (hash or hashref)
54   sub foo
55   {
56       validate( @_, { foo => 1, # mandatory
57                       bar => 0, # optional
58                     }
59               );
60   }
61
62   # takes positional params
63   sub bar
64   {
65       # first two are mandatory, third is optional
66       validate_pos( @_, 1, 1, 0 );
67   }
68
69
70   sub foo2
71   {
72       validate( @_,
73                 { foo =>
74                   # specify a type
75                   { type => ARRAYREF },
76
77                   bar =>
78                   # specify an interface
79                   { can => [ 'print', 'flush', 'frobnicate' ] },
80
81                   baz =>
82                   { type => SCALAR,   # a scalar ...
83                     # ... that is a plain integer ...
84                     regex => qr/^\d+$/,
85                     callbacks =>
86                     { # ... and smaller than 90
87                       'less than 90' => sub { shift() < 90 },
88                     },
89                   }
90                 }
91               );
92   }
93
94   sub with_defaults
95   {
96        my %p = validate( @_, { foo => 1, # required
97                                # $p{bar} will be 99 if bar is not
98                                # given.  bar is now optional.
99                                bar => { default => 99 } } );
100   }
101
102   sub pos_with_defaults
103   {
104        my @p = validate_pos( @_, 1, { default => 99 } );
105   }
106
107   sub sets_options_on_call
108   {
109        my %p = validate_with
110                    ( params => \@_,
111                      spec   => { foo => { type SCALAR, default => 2 } },
112                      normalize_keys => sub { $_[0] =~ s/^-//; lc $_[0] },
113                    );
114   }
115
116 =head1 DESCRIPTION
117
118 The Params::Validate module allows you to validate method or function
119 call parameters to an arbitrary level of specificity.  At the simplest
120 level, it is capable of validating the required parameters were given
121 and that no unspecified additional parameters were passed in.
122
123 It is also capable of determining that a parameter is of a specific
124 type, that it is an object of a certain class hierarchy, that it
125 possesses certain methods, or applying validation callbacks to
126 arguments.
127
128 =head2 EXPORT
129
130 The module always exports the C<validate()> and C<validate_pos()>
131 functions.
132
133 It also has an additional function available for export,
134 C<validate_with>, which can be used to validate any type of
135 parameters, and set various options on a per-invocation basis.
136
137 In addition, it can export the following constants, which are used as
138 part of the type checking.  These are C<SCALAR>, C<ARRAYREF>,
139 C<HASHREF>, C<CODEREF>, C<GLOB>, C<GLOBREF>, and C<SCALARREF>,
140 C<UNDEF>, C<OBJECT>, C<BOOLEAN>, and C<HANDLE>.  These are explained
141 in the section on L<Type Validation|Params::Validate/Type Validation>.
142
143 The constants are available via the export tag C<:types>.  There is
144 also an C<:all> tag which includes all of the constants as well as the
145 C<validation_options()> function.
146
147 =head1 PARAMETER VALIDATION
148
149 The validation mechanisms provided by this module can handle both
150 named or positional parameters.  For the most part, the same features
151 are available for each.  The biggest difference is the way that the
152 validation specification is given to the relevant subroutine.  The
153 other difference is in the error messages produced when validation
154 checks fail.
155
156 When handling named parameters, the module will accept either a hash
157 or a hash reference.
158
159 Subroutines expecting named parameters should call the C<validate()>
160 subroutine like this:
161
162  validate( @_, { parameter1 => validation spec,
163                  parameter2 => validation spec,
164                  ...
165                } );
166
167 Subroutines expecting positional parameters should call the
168 C<validate_pos()> subroutine like this:
169
170  validate_pos( @_, { validation spec }, { validation spec } );
171
172 =head2 Mandatory/Optional Parameters
173
174 If you just want to specify that some parameters are mandatory and
175 others are optional, this can be done very simply.
176
177 For a subroutine expecting named parameters, you would do this:
178
179  validate( @_, { foo => 1, bar => 1, baz => 0 } );
180
181 This says that the "foo" and "bar" parameters are mandatory and that
182 the "baz" parameter is optional.  The presence of any other
183 parameters will cause an error.
184
185 For a subroutine expecting positional parameters, you would do this:
186
187  validate_pos( @_, 1, 1, 0, 0 );
188
189 This says that you expect at least 2 and no more than 4 parameters.
190 If you have a subroutine that has a minimum number of parameters but
191 can take any maximum number, you can do this:
192
193  validate_pos( @_, 1, 1, (0) x (@_ - 2) );
194
195 This will always be valid as long as at least two parameters are
196 given.  A similar construct could be used for the more complex
197 validation parameters described further on.
198
199 Please note that this:
200
201  validate_pos( @_, 1, 1, 0, 1, 1 );
202
203 makes absolutely no sense, so don't do it.  Any zeros must come at the
204 end of the validation specification.
205
206 In addition, if you specify that a parameter can have a default, then
207 it is considered optional.
208
209 =head2 Type Validation
210
211 This module supports the following simple types, which can be
212 L<exported as constants|/EXPORT>:
213
214 =over 4
215
216 =item * SCALAR
217
218 A scalar which is not a reference, such as C<10> or C<'hello'>.  A
219 parameter that is undefined is B<not> treated as a scalar.  If you
220 want to allow undefined values, you will have to specify C<SCALAR |
221 UNDEF>.
222
223 =item * ARRAYREF
224
225 An array reference such as C<[1, 2, 3]> or C<\@foo>.
226
227 =item * HASHREF
228
229 A hash reference such as C<< { a => 1, b => 2 } >> or C<\%bar>.
230
231 =item * CODEREF
232
233 A subroutine reference such as C<\&foo_sub> or C<sub { print "hello" }>.
234
235 =item * GLOB
236
237 This one is a bit tricky.  A glob would be something like C<*FOO>, but
238 not C<\*FOO>, which is a glob reference.  It should be noted that this
239 trick:
240
241  my $fh = do { local *FH; };
242
243 makes C<$fh> a glob, not a glob reference.  On the other hand, the
244 return value from C<Symbol::gensym> is a glob reference.  Either can
245 be used as a file or directory handle.
246
247 =item * GLOBREF
248
249 A glob reference such as C<\*FOO>.  See the L<GLOB|GLOB> entry above
250 for more details.
251
252 =item * SCALARREF
253
254 A reference to a scalar such as C<\$x>.
255
256 =item * UNDEF
257
258 An undefined value
259
260 =item * OBJECT
261
262 A blessed reference.
263
264 =item * BOOLEAN
265
266 This is a special option, and is just a shortcut for C<UNDEF | SCALAR>.
267
268 =item * HANDLE
269
270 This option is also special, and is just a shortcut for C<GLOB |
271 GLOBREF>.  However, it seems likely that most people interested in
272 either globs or glob references are likely to really be interested in
273 whether the parameter in question could be a valid file or directory
274 handle.
275
276 =back
277
278 To specify that a parameter must be of a given type when using named
279 parameters, do this:
280
281  validate( @_, { foo => { type => SCALAR },
282                  bar => { type => HASHREF } } );
283
284 If a parameter can be of more than one type, just use the bitwise or
285 (C<|>) operator to combine them.
286
287  validate( @_, { foo => { type => GLOB | GLOBREF } );
288
289 For positional parameters, this can be specified as follows:
290
291  validate_pos( @_, { type => SCALAR | ARRAYREF }, { type => CODEREF } );
292
293 =head2 Interface Validation
294
295 To specify that a parameter is expected to have a certain set of
296 methods, we can do the following:
297
298  validate( @_,
299            { foo =>
300              # just has to be able to ->bar
301              { can => 'bar' } } );
302
303  ... or ...
304
305  validate( @_,
306            { foo =>
307              # must be able to ->bar and ->print
308              { can => [ qw( bar print ) ] } } );
309
310 =head2 Class Validation
311
312 A word of warning.  When constructing your external interfaces, it is
313 probably better to specify what methods you expect an object to
314 have rather than what class it should be of (or a child of).  This
315 will make your API much more flexible.
316
317 With that said, if you want to validate that an incoming parameter
318 belongs to a class (or child class) or classes, do:
319
320  validate( @_,
321            { foo =>
322              { isa => 'My::Frobnicator' } } );
323
324  ... or ...
325
326  validate( @_,
327            { foo =>
328              { isa => [ qw( My::Frobnicator IO::Handle ) ] } } );
329  # must be both, not either!
330
331 =head2 Regex Validation
332
333 If you want to specify that a given parameter must match a specific
334 regular expression, this can be done with "regex" spec key.  For
335 example:
336
337
338  validate( @_,
339            { foo =>
340              { regex => qr/^\d+$/ } } );
341
342 The value of the "regex" key may be either a string or a pre-compiled
343 regex created via C<qr>.
344
345 If the value being checked against a regex is undefined, the regex is
346 explicitly checked against the empty string ('') instead, in order to
347 avoid "Use of uninitialized value" warnings.
348
349 The C<Regexp::Common> module on CPAN is an excellent source of regular
350 expressions suitable for validating input.
351
352 =head2 Callback Validation
353
354 If none of the above are enough, it is possible to pass in one or more
355 callbacks to validate the parameter.  The callback will be given the
356 B<value> of the parameter as its first argument.  Its second argument
357 will be all the parameters, as a reference to either a hash or array.
358 Callbacks are specified as hash reference.  The key is an id for the
359 callback (used in error messages) and the value is a subroutine
360 reference, such as:
361
362  validate( @_,
363            { foo =>
364              { callbacks =>
365                { 'smaller than a breadbox' => sub { shift() < $breadbox },
366                  'green or blue' =>
367                   sub { $_[0] eq 'green' || $_[0] eq 'blue' } } } );
368
369  validate( @_,
370            { foo =>
371              { callbacks =>
372                { 'bigger than baz' => sub { $_[0] > $_[1]->{baz} } } } } );
373
374 =head2 Untainting
375
376 If you want values untainted, set the "untaint" key in a spec hashref
377 to a true value, like this:
378
379  my %p =
380    validate( @_, { foo =>
381                    { type => SCALAR, untaint => 1 },
382                    bar =>
383                    { type => ARRAYREF } } );
384
385 This will untaint the "foo" parameter if the parameters are valid.
386
387 Note that untainting is only done if I<all parameters> are valid.
388 Also, only the return values are untainted, not the original values
389 passed into the validation function.
390
391 Asking for untainting of a reference value will not do anything, as
392 C<Params::Validate> will only attempt to untaint the reference itself.
393
394 =head2 Mandatory/Optional Revisited
395
396 If you want to specify something such as type or interface, plus the
397 fact that a parameter can be optional, do this:
398
399  validate( @_, { foo =>
400                  { type => SCALAR },
401                  bar =>
402                  { type => ARRAYREF, optional => 1 } } );
403
404 or this for positional parameters:
405
406  validate_pos( @_, { type => SCALAR }, { type => ARRAYREF, optional => 1 } );
407
408 By default, parameters are assumed to be mandatory unless specified as
409 optional.
410
411 =head2 Dependencies
412
413 It also possible to specify that a given optional parameter depends on
414 the presence of one or more other optional parameters.
415
416  validate( @_, { cc_number =>
417                  { type => SCALAR, optional => 1,
418                    depends => [ 'cc_expiration', 'cc_holder_name' ],
419                  },
420                  cc_expiration
421                  { type => SCALAR, optional => 1 },
422                  cc_holder_name
423                  { type => SCALAR, optional => 1 },
424                } );
425
426 In this case, "cc_number", "cc_expiration", and "cc_holder_name" are
427 all optional.  However, if "cc_number" is provided, then
428 "cc_expiration" and "cc_holder_name" must be provided as well.
429
430 This allows you to group together sets of parameters that all must be
431 provided together.
432
433 The C<validate_pos()> version of dependencies is slightly different,
434 in that you can only depend on one other parameter.  Also, if for
435 example, the second parameter 2 depends on the fourth parameter, then
436 it implies a dependency on the third parameter as well.  This is
437 because if the fourth parameter is required, then the user must also
438 provide a third parameter so that there can be four parameters in
439 total.
440
441 C<Params::Validate> will die if you try to depend on a parameter not
442 declared as part of your parameter specification.
443
444 =head2 Specifying defaults
445
446 If the C<validate()> or C<validate_pos()> functions are called in a
447 list context, they will return an array or hash containing the
448 original parameters plus defaults as indicated by the validation spec.
449
450 If the function is not called in a list context, providing a default
451 in the validation spec still indicates that the parameter is optional.
452
453 The hash or array returned from the function will always be a copy of
454 the original parameters, in order to leave C<@_> untouched for the
455 calling function.
456
457 Simple examples of defaults would be:
458
459  my %p = validate( @_, { foo => 1, bar => { default => 99 } } );
460
461  my @p = validate( @_, 1, { default => 99 } );
462
463 In scalar context, a hash reference or array reference will be
464 returned, as appropriate.
465
466 =head1 USAGE NOTES
467
468 =head2 Validation failure
469
470 By default, when validation fails C<Params::Validate> calls
471 C<Carp::confess()>.  This can be overridden by setting the C<on_fail>
472 option, which is described in the L<"GLOBAL" OPTIONS|"GLOBAL" OPTIONS>
473 section.
474
475 =head2 Method calls
476
477 When using this module to validate the parameters passed to a method
478 call, you will probably want to remove the class/object from the
479 parameter list B<before> calling C<validate()> or C<validate_pos()>.
480 If your method expects named parameters, then this is necessary for
481 the C<validate()> function to actually work, otherwise C<@_> will not
482 be useable as a hash, because it will first have your object (or
483 class) B<followed> by a set of keys and values.
484
485 Thus the idiomatic usage of C<validate()> in a method call will look
486 something like this:
487
488  sub method
489  {
490      my $self = shift;
491
492      my %params = validate( @_, { foo => 1, bar => { type => ARRAYREF } } );
493  }
494
495 =head1 "GLOBAL" OPTIONS
496
497 Because the API for the C<validate()> and C<validate_pos()> functions
498 does not make it possible to specify any options other than the the
499 validation spec, it is possible to set some options as
500 pseudo-'globals'.  These allow you to specify such things as whether
501 or not the validation of named parameters should be case sensitive,
502 for one example.
503
504 These options are called pseudo-'globals' because these settings are
505 B<only applied to calls originating from the package that set the
506 options>.
507
508 In other words, if I am in package C<Foo> and I call
509 C<validation_options()>, those options are only in effect when I call
510 C<validate()> from package C<Foo>.
511
512 While this is quite different from how most other modules operate, I
513 feel that this is necessary in able to make it possible for one
514 module/application to use Params::Validate while still using other
515 modules that also use Params::Validate, perhaps with different
516 options set.
517
518 The downside to this is that if you are writing an app with a standard
519 calling style for all functions, and your app has ten modules, B<each
520 module must include a call to C<validation_options()>>. You could of
521 course write a module that all your modules use which uses various
522 trickery to do this when imported.
523
524 =head2 Options
525
526 =over 4
527
528 =item * normalize_keys => $callback
529
530 This option is only relevant when dealing with named parameters.
531
532 This callback will be used to transform the hash keys of both the
533 parameters and the parameter spec when C<validate()> or
534 C<validate_with()> are called.
535
536 Any alterations made by this callback will be reflected in the
537 parameter hash that is returned by the validation function.  For
538 example:
539
540   sub foo {
541       return
542         validate_with( params => \@_,
543                        spec   => { foo => { type => SCALAR } },
544                        normalize_keys =>
545                        sub { my $k = shift; $k =~ s/^-//; return uc $k },
546                      );
547
548   }
549
550   %p = foo( foo => 20 );
551
552   # $p{FOO} is now 20
553
554   %p = foo( -fOo => 50 );
555
556   # $p{FOO} is now 50
557
558 The callback must return a defined value.
559
560 If a callback is given than the deprecated "ignore_case" and
561 "strip_leading" options are ignored.
562
563 =item * allow_extra => $boolean
564
565 If true, then the validation routine will allow extra parameters not
566 named in the validation specification.  In the case of positional
567 parameters, this allows an unlimited number of maximum parameters
568 (though a minimum may still be set).  Defaults to false.
569
570 =item * on_fail => $callback
571
572 If given, this callback will be called whenever a validation check
573 fails.  It will be called with a single parameter, which will be a
574 string describing the failure.  This is useful if you wish to have
575 this module throw exceptions as objects rather than as strings, for
576 example.
577
578 This callback is expected to C<die()> internally.  If it does not, the
579 validation will proceed onwards, with unpredictable results.
580
581 The default is to simply use the Carp module's C<confess()> function.
582
583 =item * stack_skip => $number
584
585 This tells Params::Validate how many stack frames to skip when finding
586 a subroutine name to use in error messages.  By default, it looks one
587 frame back, at the immediate caller to C<validate()> or
588 C<validate_pos()>.  If this option is set, then the given number of
589 frames are skipped instead.
590
591 =item * ignore_case => $boolean
592
593 DEPRECATED
594
595 This is only relevant when dealing with named parameters.  If it is
596 true, then the validation code will ignore the case of parameter
597 names.  Defaults to false.
598
599 =item * strip_leading => $characters
600
601 DEPRECATED
602
603 This too is only relevant when dealing with named parameters.  If this
604 is given then any parameters starting with these characters will be
605 considered equivalent to parameters without them entirely.  For
606 example, if this is specified as '-', then C<-foo> and C<foo> would be
607 considered identical.
608
609 =back
610
611 =head1 PER-INVOCATION OPTIONS
612
613 The C<validate_with()> function can be used to set the options listed
614 above on a per-invocation basis.  For example:
615
616   my %p =
617       validate_with
618           ( params => \@_,
619             spec   => { foo => { type => SCALAR },
620                         bar => { default => 10 } },
621             allow_extra => 1,
622           );
623
624 In addition to the options listed above, it is also possible to set
625 the option "called", which should be a string.  This string will be
626 used in any error messages caused by a failure to meet the validation
627 spec.
628
629 This subroutine will validate named parameters as a hash if the "spec"
630 parameter is a hash reference.  If it is an array reference, the
631 parameters are assumed to be positional.
632
633   my %p =
634       validate_with
635           ( params => \@_,
636             spec   => { foo => { type => SCALAR },
637                         bar => { default => 10 } },
638             allow_extra => 1,
639             called => 'The Quux::Baz class constructor',
640           );
641
642   my @p =
643       validate_with
644           ( params => \@_,
645             spec   => [ { type => SCALAR },
646                         { default => 10 } ],
647             allow_extra => 1,
648             called => 'The Quux::Baz class constructor',
649           );
650
651 =head1 DISABLING VALIDATION
652
653 If the environment variable C<PERL_NO_VALIDATION> is set to something
654 true, then validation is turned off.  This may be useful if you only
655 want to use this module during development but don't want the speed
656 hit during production.
657
658 The only error that will be caught will be when an odd number of
659 parameters are passed into a function/method that expects a hash.
660
661 If you want to selectively turn validation on and off at runtime, you
662 can directly set the C<$Params::Validate::NO_VALIDATION> global
663 variable.  It is B<strongly> recommended that you B<localize> any
664 changes to this variable, because other modules you are using may
665 expect validation to be on when they execute.  For example:
666
667
668   {
669       local $Params::Validate::NO_VALIDATION = 1;
670       # no error
671       foo( bar => 2 );
672   }
673
674   # error
675   foo( bar => 2 );
676
677   sub foo
678   {
679       my %p = validate( @_, { foo => 1 } );
680       ...
681   }
682
683 But if you want to shoot yourself in the foot and just turn it off, go
684 ahead!
685
686 =head1 LIMITATIONS
687
688 Right now there is no way (short of a callback) to specify that
689 something must be of one of a list of classes, or that it must possess
690 one of a list of methods.  If this is desired, it can be added in the
691 future.
692
693 Ideally, there would be only one validation function.  If someone
694 figures out how to do this, please let me know.
695
696 =head1 SUPPORT
697
698 Please submit bugs and patches to the CPAN RT system at
699 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Params%3A%3AValidate or
700 via email at bug-params-validate@rt.cpan.org.
701
702 Support questions can be sent to Dave at autarch@urth.org.
703
704 The code repository is at https://svn.urth.org/svn/Params-Validate/
705
706 =head1 DONATIONS
707
708 If you'd like to thank me for the work I've done on this module,
709 please consider making a "donation" to me via PayPal. I spend a lot of
710 free time creating free software, and would appreciate any support
711 you'd care to offer.
712
713 Please note that B<I am not suggesting that you must do this> in order
714 for me to continue working on this particular software. I will
715 continue to do so, inasmuch as I have in the past, for as long as it
716 interests me.
717
718 Similarly, a donation made in this way will probably not make me work
719 on this software much more, unless I get so many donations that I can
720 consider working on free software full time, which seems unlikely at
721 best.
722
723 To donate, log into PayPal and send money to autarch@urth.org or use
724 the button on this page:
725 L<http://www.urth.org/~autarch/fs-donation.html>
726
727 =head1 AUTHORS
728
729 Dave Rolsky, <autarch@urth.org> and Ilya Martynov <ilya@martynov.org>
730
731 =head1 COPYRIGHT
732
733 Copyright (c) 2004-2007 David Rolsky.  All rights reserved.  This
734 program is free software; you can redistribute it and/or modify it
735 under the same terms as Perl itself.
736
737 =cut