home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Validate.pm < prev    next >
Encoding:
Perl POD Document  |  2003-12-03  |  20.5 KB  |  699 lines

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