adding support for checking container types in the constructor
[gitmo/MooseX-AttributeHelpers.git] / lib / MooseX / AttributeHelpers / Collection.pm
CommitLineData
8c651099 1
2package MooseX::AttributeHelpers::Collection;
3use Moose;
4use Moose::Util::TypeConstraints;
5
6our $VERSION = '0.01';
7our $AUTHORITY = 'cpan:STEVAN';
8
9extends 'MooseX::AttributeHelpers::Base';
10
11has 'container_type' => (
12 is => 'ro',
13 isa => 'Str',
14 predicate => 'has_container_type',
15);
16
17has 'container_type_constraint' => (
77d02b8b 18 is => 'rw',
19 isa => 'Moose::Meta::TypeConstraint',
20 required => 1,
8c651099 21);
22
23before 'process_options_for_provides' => sub {
24 my ($self, $options) = @_;
25
26 if (exists $options->{isa}) {
27 my $type = $options->{isa};
77d02b8b 28
29 # ... we should check if the type exists already
30 # and then we should use it,.. however, this means
31 # we need to extract the container type constraint
32 # as well, which is a little trickier
33
8c651099 34 if ($type =~ /^(.*)\[(.*)\]$/) {
35 my $core_type = $1;
36 my $container_type = $2;
77d02b8b 37
8c651099 38 $options->{container_type} = $container_type;
77d02b8b 39
40 my $container_type_constraint = find_type_constraint($container_type);
41
42 # NOTE:
43 # I am not sure DWIM-ery is a good thing
44 # here, so i am going to err on the side
45 # of caution, and blow up if you have
46 # not made a type constraint for this yet.
47 # - SL
48 (defined $container_type_constraint)
49 || confess "You must predefine the '$container_type' constraint before you can use it as a container type";
50
51 $options->{container_type_constraint} = $container_type_constraint;
52
53 if ($core_type eq 'ArrayRef') {
54 $options->{isa} = subtype('ArrayRef' => where {
55 foreach my $x (@$_) { ($container_type_constraint->check($x)) || return } 1;
56 });
57 }
58 elsif ($core_type eq 'HashRef') {
59 $options->{isa} = subtype('HashRef' => where {
60 foreach my $x (values %$_) { ($container_type_constraint->check($x)) || return } 1;
61 });
62 }
63 else {
64 confess "Your isa must be either ArrayRef or HashRef (sorry no subtype support yet)";
65 }
8c651099 66 }
67 }
68};
69
70no Moose;
c25a396f 71no Moose::Util::TypeConstraints;
8c651099 72
731;
74
75__END__
76
77=pod
78
79=head1 NAME
80
81=head1 SYNOPSIS
82
83=head1 DESCRIPTION
84
85=head1 METHODS
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 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