type-coercion-meta-object
[gitmo/Moose.git] / lib / Moose / Meta / TypeConstraint.pm
CommitLineData
4e036ee4 1
2package Moose::Meta::TypeConstraint;
3
4use strict;
5use warnings;
6use metaclass;
7
66811d63 8use Sub::Name 'subname';
9use Carp 'confess';
10
11our $VERSION = '0.01';
12
66811d63 13__PACKAGE__->meta->add_attribute('name' => (reader => 'name' ));
14__PACKAGE__->meta->add_attribute('parent' => (reader => 'parent' ));
15__PACKAGE__->meta->add_attribute('constraint' => (reader => 'constraint'));
a27aa600 16__PACKAGE__->meta->add_attribute('coercion' => (
17 accessor => 'coercion',
18 predicate => 'has_coercion'
19));
66811d63 20
21# private accessor
22__PACKAGE__->meta->add_attribute('compiled_type_constraint' => (
23 accessor => '_compiled_type_constraint'
24));
25
66811d63 26sub new {
a27aa600 27 my $class = shift;
28 my $self = $class->meta->new_object(@_);
66811d63 29 $self->compile_type_constraint();
30 return $self;
31}
32
33sub compile_type_constraint () {
a27aa600 34 my $self = shift;
35 my $check = $self->constraint;
66811d63 36 (defined $check)
37 || confess "Could not compile type constraint '" . $self->name . "' because no constraint check";
38 my $parent = $self->parent;
39 if (defined $parent) {
a27aa600 40 # we have a subtype ...
66811d63 41 $parent = $parent->_compiled_type_constraint;
42 $self->_compiled_type_constraint(subname $self->name => sub {
43 local $_ = $_[0];
44 return undef unless defined $parent->($_[0]) && $check->($_[0]);
45 $_[0];
46 });
47 }
48 else {
a27aa600 49 # we have a type ....
66811d63 50 $self->_compiled_type_constraint(subname $self->name => sub {
51 local $_ = $_[0];
52 return undef unless $check->($_[0]);
53 $_[0];
54 });
55 }
56}
57
a27aa600 58sub check { $_[0]->_compiled_type_constraint->($_[1]) }
4e036ee4 59
601;
61
62__END__
63
64=pod
65
66=head1 NAME
67
68Moose::Meta::TypeConstraint - The Moose Type Constraint metaobject
69
70=head1 SYNOPSIS
71
72=head1 DESCRIPTION
73
74=head1 METHODS
75
76=over 4
77
78=item B<meta>
79
80=item B<new>
81
82=item B<name>
83
66811d63 84=item B<parent>
85
4e036ee4 86=item B<check>
87
66811d63 88=item B<constraint>
89
4e036ee4 90=item B<has_coercion>
91
a27aa600 92=item B<coercion>
93
66811d63 94=item B<compile_type_constraint>
95
4e036ee4 96=back
97
98=head1 BUGS
99
100All complex software has bugs lurking in it, and this module is no
101exception. If you find a bug please either email me, or add the bug
102to cpan-RT.
103
104=head1 AUTHOR
105
106Stevan Little E<lt>stevan@iinteractive.comE<gt>
107
108=head1 COPYRIGHT AND LICENSE
109
110Copyright 2006 by Infinity Interactive, Inc.
111
112L<http://www.iinteractive.com>
113
114This library is free software; you can redistribute it and/or modify
115it under the same terms as Perl itself.
116
117=cut