1 package Moose::Meta::TypeConstraint::Parameterized;
7 use Scalar::Util 'blessed';
9 use Moose::Util::TypeConstraints;
11 our $VERSION = '0.02';
12 our $AUTHORITY = 'cpan:STEVAN';
14 use base 'Moose::Meta::TypeConstraint';
16 __PACKAGE__->meta->add_attribute('type_parameter' => (
17 accessor => 'type_parameter',
18 predicate => 'has_type_parameter',
21 sub compile_type_constraint {
24 ($self->has_type_parameter)
25 || confess "You cannot create a Higher Order type without a type parameter";
27 my $type_parameter = $self->type_parameter;
29 (blessed $type_parameter && $type_parameter->isa('Moose::Meta::TypeConstraint'))
30 || confess "The type parameter must be a Moose meta type";
33 my $name = $self->parent->name;
36 Moose::Util::TypeConstraints::find_type_constraint('ArrayRef')
40 Moose::Util::TypeConstraints::find_type_constraint('HashRef')
43 # ArrayRef[Foo] will check each element for the Foo constraint
44 my $array_constraint = sub {
46 ($type_parameter->check($x)) || return
50 # HashRef[Foo] will check each value for the Foo constraint
51 my $hash_constraint = sub {
52 foreach my $x (values %$_) {
53 ($type_parameter->check($x)) || return
57 # if this is a subtype of ArrayRef, then we can use the ArrayRef[Foo]
59 if ($self->is_subtype_of('ArrayRef')) {
60 $constraint = $array_constraint;
62 # if this is a subtype of HashRef, then we can use the HashRef[Foo]
64 elsif ($self->is_subtype_of('HashRef')) {
65 $constraint = $hash_constraint;
67 # if we can coerce this type to an ArrayRef, do it and use the regular
68 # ArrayRef[Foo] constraint
69 elsif ($array_coercion && $array_coercion->has_coercion_for_type($name)) {
71 local $_ = $array_coercion->coerce($_);
72 $array_constraint->(@_);
75 # if we can coerce this type to a HashRef, do it and use the regular
76 # HashRef[Foo] constraint
77 elsif ($hash_coercion && $hash_coercion->has_coercion_for_type($name)) {
79 local $_ = $hash_coercion->coerce($_);
80 $hash_constraint->(@_);
84 confess "The " . $self->name . " constraint cannot be used, because " . $name . " doesn't subtype or coerce ArrayRef or HashRef.";
87 $self->_set_constraint($constraint);
89 $self->SUPER::compile_type_constraint;
101 Moose::Meta::TypeConstraint::Parameterized - Higher Order type constraints for Moose
109 =item B<compile_type_constraint>
111 =item B<type_parameter>
113 =item B<has_type_parameter>
121 All complex software has bugs lurking in it, and this module is no
122 exception. If you find a bug please either email me, or add the bug
127 Stevan Little E<lt>stevan@iinteractive.comE<gt>
129 =head1 COPYRIGHT AND LICENSE
131 Copyright 2006-2008 by Infinity Interactive, Inc.
133 L<http://www.iinteractive.com>
135 This library is free software; you can redistribute it and/or modify
136 it under the same terms as Perl itself.