Add support for parametric containers that subtype ArrayRef or HashRef
[gitmo/Moose.git] / lib / Moose / Meta / TypeConstraint / Parameterized.pm
CommitLineData
0fbd4b0a 1package Moose::Meta::TypeConstraint::Parameterized;
d67145ed 2
3use strict;
4use warnings;
5use metaclass;
6
7use Scalar::Util 'blessed';
8use Carp 'confess';
9
10our $VERSION = '0.01';
11our $AUTHORITY = 'cpan:STEVAN';
12
13use base 'Moose::Meta::TypeConstraint';
14
0fbd4b0a 15__PACKAGE__->meta->add_attribute('type_parameter' => (
16 accessor => 'type_parameter',
17 predicate => 'has_type_parameter',
d67145ed 18));
19
20sub compile_type_constraint {
21 my $self = shift;
22
0fbd4b0a 23 ($self->has_type_parameter)
24 || confess "You cannot create a Higher Order type without a type parameter";
d67145ed 25
0fbd4b0a 26 my $type_parameter = $self->type_parameter;
d67145ed 27
0fbd4b0a 28 (blessed $type_parameter && $type_parameter->isa('Moose::Meta::TypeConstraint'))
29 || confess "The type parameter must be a Moose meta type";
d67145ed 30
31 my $constraint;
32
39aba5c9 33 my $array_constraint = sub {
34 foreach my $x (@$_) {
35 ($type_parameter->check($x)) || return
36 } 1;
37 };
38
39 my $hash_constraint = sub {
40 foreach my $x (values %$_) {
41 ($type_parameter->check($x)) || return
42 } 1;
43 };
44
45 if ($self->is_subtype_of('ArrayRef')) {
46 $constraint = $array_constraint;
d67145ed 47 }
39aba5c9 48 elsif ($self->is_subtype_of('HashRef')) {
49 $constraint = $hash_constraint;
d67145ed 50 }
51 else {
39aba5c9 52 confess "The " . $self->name . " constraint cannot be used, because " . $self->parent->name . " doesn't subtype ArrayRef or HashRef.";
d67145ed 53 }
54
55 $self->_set_constraint($constraint);
56
57 $self->SUPER::compile_type_constraint;
58}
59
601;
61
62__END__
63
64
65=pod
66
67=head1 NAME
68
0fbd4b0a 69Moose::Meta::TypeConstraint::Parameterized - Higher Order type constraints for Moose
d67145ed 70
71=head1 DESCRIPTION
72
73=head1 METHODS
74
75=over 4
76
77=item B<compile_type_constraint>
78
0fbd4b0a 79=item B<type_parameter>
d67145ed 80
0fbd4b0a 81=item B<has_type_parameter>
d67145ed 82
83=item B<meta>
84
85=back
86
87=head1 BUGS
88
89All complex software has bugs lurking in it, and this module is no
90exception. If you find a bug please either email me, or add the bug
91to cpan-RT.
92
93=head1 AUTHOR
94
95Stevan Little E<lt>stevan@iinteractive.comE<gt>
96
97=head1 COPYRIGHT AND LICENSE
98
99Copyright 2006, 2007 by Infinity Interactive, Inc.
100
101L<http://www.iinteractive.com>
102
103This library is free software; you can redistribute it and/or modify
104it under the same terms as Perl itself.
105
106=cut