1 package MooseX::Params::Validate;
7 use Devel::Caller 'caller_cv';
8 use Scalar::Util 'blessed', 'refaddr', 'reftype';
10 use Moose::Util::TypeConstraints qw( find_type_constraint class_type role_type );
11 use Params::Validate ();
12 use Sub::Exporter -setup => {
14 qw( validated_hash validated_list pos_validated_list validate validatep )
17 default => [qw( validated_hash validated_list pos_validated_list )],
18 deprecated => [qw( validate validatep )],
25 my ( $args, %spec ) = @_;
27 my $cache_key = _cache_key( \%spec );
29 my $allow_extra = delete $spec{MX_PARAMS_VALIDATE_ALLOW_EXTRA};
31 if ( exists $CACHED_SPECS{$cache_key} ) {
32 ( ref $CACHED_SPECS{$cache_key} eq 'HASH' )
34 "I was expecting a HASH-ref in the cached $cache_key parameter"
35 . " spec, you are doing something funky, stop it!";
36 %spec = %{ $CACHED_SPECS{$cache_key} };
39 my $should_cache = delete $spec{MX_PARAMS_VALIDATE_NO_CACHE} ? 0 : 1;
41 $spec{$_} = _convert_to_param_validate_spec( $spec{$_} )
44 $CACHED_SPECS{$cache_key} = \%spec
49 $instance = shift @$args if blessed $args->[0];
54 && reftype( $args->[0] ) eq 'HASH' ? %{ $args->[0] } : @$args;
56 $args{$_} = $spec{$_}{constraint}->coerce( $args{$_} )
57 for grep { $spec{$_}{coerce} && exists $args{$_} } keys %spec;
59 %args = Params::Validate::validate_with(
62 allow_extra => $allow_extra,
63 called => _caller_name(),
66 return ( ( defined $instance ? $instance : () ), %args );
69 *validate = \&validated_hash;
72 my ( $args, @spec ) = @_;
76 my $cache_key = _cache_key( \%spec );
78 my $allow_extra = delete $spec{MX_PARAMS_VALIDATE_ALLOW_EXTRA};
81 if ( exists $CACHED_SPECS{$cache_key} ) {
82 ( ref $CACHED_SPECS{$cache_key} eq 'ARRAY' )
84 "I was expecting a ARRAY-ref in the cached $cache_key parameter"
85 . " spec, you are doing something funky, stop it!";
86 %spec = %{ $CACHED_SPECS{$cache_key}->[0] };
87 @ordered_spec = @{ $CACHED_SPECS{$cache_key}->[1] };
90 my $should_cache = delete $spec{MX_PARAMS_VALIDATE_NO_CACHE} ? 0 : 1;
92 @ordered_spec = grep { exists $spec{$_} } @spec;
94 $spec{$_} = _convert_to_param_validate_spec( $spec{$_} )
97 $CACHED_SPECS{$cache_key} = [ \%spec, \@ordered_spec ]
102 $instance = shift @$args if blessed $args->[0];
107 && reftype( $args->[0] ) eq 'HASH' ? %{ $args->[0] } : @$args;
109 $args{$_} = $spec{$_}{constraint}->coerce( $args{$_} )
110 for grep { $spec{$_}{coerce} && exists $args{$_} } keys %spec;
112 %args = Params::Validate::validate_with(
115 allow_extra => $allow_extra,
116 called => _caller_name(),
120 ( defined $instance ? $instance : () ),
125 *validatep = \&validated_list;
127 sub pos_validated_list {
131 push @spec, shift while ref $_[0];
135 my $cache_key = _cache_key( \%extra );
137 my $allow_extra = delete $extra{MX_PARAMS_VALIDATE_ALLOW_EXTRA};
140 if ( exists $CACHED_SPECS{$cache_key} ) {
141 ( ref $CACHED_SPECS{$cache_key} eq 'ARRAY' )
143 "I was expecting an ARRAY-ref in the cached $cache_key parameter"
144 . " spec, you are doing something funky, stop it!";
145 @pv_spec = @{ $CACHED_SPECS{$cache_key} };
148 my $should_cache = exists $extra{MX_PARAMS_VALIDATE_NO_CACHE} ? 0 : 1;
150 # prepare the parameters ...
151 @pv_spec = map { _convert_to_param_validate_spec($_) } @spec;
153 $CACHED_SPECS{$cache_key} = \@pv_spec
160 && reftype( $args->[0] ) eq 'ARRAY' ? @{ $args->[0] } : @$args;
162 $args[$_] = $pv_spec[$_]{constraint}->coerce( $args[$_] )
163 for grep { $pv_spec[$_] && $pv_spec[$_]{coerce} } 0 .. $#args;
165 @args = Params::Validate::validate_with(
168 allow_extra => $allow_extra,
169 called => _caller_name(),
178 if ( exists $spec->{MX_PARAMS_VALIDATE_CACHE_KEY} ) {
179 return delete $spec->{MX_PARAMS_VALIDATE_CACHE_KEY};
182 return refaddr( caller_cv(2) );
186 sub _convert_to_param_validate_spec {
190 $pv_spec{optional} = $spec->{optional}
191 if exists $spec->{optional};
193 $pv_spec{default} = $spec->{default}
194 if exists $spec->{default};
196 $pv_spec{coerce} = $spec->{coerce}
197 if exists $spec->{coerce};
200 if ( defined $spec->{isa} ) {
202 = _is_tc( $spec->{isa} )
203 || Moose::Util::TypeConstraints::find_or_parse_type_constraint(
205 || class_type( $spec->{isa} );
207 elsif ( defined $spec->{does} ) {
209 = _is_tc( $spec->{isa} )
210 || find_type_constraint( $spec->{does} )
211 || role_type( $spec->{does} );
214 $pv_spec{callbacks} = $spec->{callbacks}
215 if exists $spec->{callbacks};
218 $pv_spec{constraint} = $constraint;
221 { 'checking type constraint for ' . $constraint->name }
222 = sub { $constraint->check( $_[0] ) };
225 delete $pv_spec{coerce}
226 unless $pv_spec{constraint} && $pv_spec{constraint}->has_coercion;
232 my $maybe_tc = shift;
237 && $maybe_tc->isa('Moose::Meta::TypeConstraint');
241 my $depth = shift || 0;
243 return ( caller( 2 + $depth ) )[3];
248 # ABSTRACT: an extension of Params::Validate using Moose's types
258 use MooseX::Params::Validate;
261 my ( $self, %params ) = validated_hash(
263 bar => { isa => 'Str', default => 'Moose' },
265 return "Hooray for $params{bar}!";
270 my ( $foo, $baz, $gorch ) = validated_list(
272 foo => { isa => 'Foo' },
273 baz => { isa => 'ArrayRef | HashRef', optional => 1 },
274 gorch => { isa => 'ArrayRef[Int]', optional => 1 }
276 [ $foo, $baz, $gorch ];
281 This module fills a gap in Moose by adding method parameter validation
282 to Moose. This is just one of many developing options, it should not
283 be considered the "official" one by any means though.
285 You might also want to explore C<MooseX::Method::Signatures> and
290 It is not possible to introspect the method parameter specs; they are
291 created as needed when the method is called and cached for subsequent
298 =item B<validated_hash( \@_, %parameter_spec )>
300 This behaves similarly to the standard Params::Validate C<validate>
301 function and returns the captured values in a HASH. The one exception
302 is where if it spots an instance in the C<@_>, then it will handle
303 it appropriately (unlike Params::Validate which forces you to shift
306 The C<%parameter_spec> accepts the following options:
312 The C<isa> option can be either; class name, Moose type constraint
313 name or an anon Moose type constraint.
317 The C<does> option can be either; role name or an anon Moose type
322 This is the default value to be used if the value is not supplied.
326 As with Params::Validate, all options are considered required unless
327 otherwise specified. This option is passed directly to
332 If this is true and the parameter has a type constraint which has
333 coercions, then the coercion will be called for this parameter. If the
334 type does have coercions, then this parameter is ignored.
338 This function is also available under its old name, C<validate>.
340 =item B<validated_list( \@_, %parameter_spec )>
342 The C<%parameter_spec> accepts the same options as above, but returns
343 the parameters as positional values instead of a HASH. This is best
344 explained by example:
347 my ( $self, $foo, $bar ) = validated_list(
349 foo => { isa => 'Foo' },
350 bar => { isa => 'Bar' },
355 We capture the order in which you defined the parameters and then
356 return them as a list in the same order. If a param is marked optional
357 and not included, then it will be set to C<undef>.
359 Like C<validated_hash>, if it spots an object instance as the first
360 parameter of C<@_>, it will handle it appropriately, returning it as
363 This function is also available under its old name, C<validatep>.
365 =item B<pos_validated_list( \@_, $spec, $spec, ... )>
367 This function validates a list of positional parameters. Each C<$spec>
368 should validate one of the parameters in the list:
372 my ( $foo, $bar ) = pos_validated_list(
381 Unlike the other functions, this function I<cannot> find C<$self> in
382 the argument list. Make sure to shift it off yourself before doing
385 If a parameter is marked as optional and is not present, it will
386 simply not be returned.
388 If you want to pass in any of the cache control parameters described
389 below, simply pass them after the list of parameter validation specs:
393 my ( $foo, $bar ) = pos_validated_list(
397 MX_PARAMS_VALIDATE_NO_CACHE => 1,
405 =head1 ALLOWING EXTRA PARAMETERS
407 By default, any parameters not mentioned in the parameter spec cause this
408 module to throw an error. However, you can have have this module simply ignore
409 them by setting C<MX_PARAMS_VALIDATE_ALLOW_EXTRA> to a true value when calling
410 a validation subroutine.
412 When calling C<validated_hash> or C<pos_validated_list> the extra parameters
413 are simply returned in the hash or list as appropriate. However, when you call
414 C<validated_list> the extra parameters will not be returned at all. You can
415 get them by looking at the original value of C<@_>.
419 By default, this module exports the C<validated_hash>,
420 C<validated_list>, and C<pos_validated_list>.
422 If you would prefer to import the now deprecated functions C<validate>
423 and C<validatep> instead, you can use the C<:deprecated> tag to import
426 =head1 IMPORTANT NOTE ON CACHING
428 When a validation subroutine is called the first time, the parameter spec is
429 prepared and cached to avoid unnecessary regeneration. It uses the fully
430 qualified name of the subroutine (package + subname) as the cache key. In
431 99.999% of the use cases for this module, that will be the right thing to do.
433 However, I have (ab)used this module occasionally to handle dynamic
434 sets of parameters. In this special use case you can do a couple
435 things to better control the caching behavior.
441 Passing in the C<MX_PARAMS_VALIDATE_NO_CACHE> flag in the parameter
442 spec this will prevent the parameter spec from being cached.
445 my ( $self, %params ) = validated_hash(
447 foo => { isa => 'Foo' },
448 MX_PARAMS_VALIDATE_NO_CACHE => 1,
455 Passing in C<MX_PARAMS_VALIDATE_CACHE_KEY> with a value to be used as
456 the cache key will bypass the normal cache key generation.
459 my ( $self, %params ) = validated_hash(
461 foo => { isa => 'Foo' },
462 MX_PARAMS_VALIDATE_CACHE_KEY => 'foo-42',
471 Dave Rolsky E<lt>autarch@urth.orgE<gt>
475 Please submit bugs to the CPAN RT system at
476 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=moosex-params-validate or via
477 email at bug-moosex-params-validate@rt.cpan.org.