2 package Moose::Meta::TypeCoercion;
10 use Moose::Meta::Attribute;
11 use Moose::Util::TypeConstraints ();
13 our $VERSION = '0.56';
14 $VERSION = eval $VERSION;
15 our $AUTHORITY = 'cpan:STEVAN';
17 __PACKAGE__->meta->add_attribute('type_coercion_map' => (
18 reader => 'type_coercion_map',
22 __PACKAGE__->meta->add_attribute(
23 Moose::Meta::Attribute->new('type_constraint' => (
24 reader => 'type_constraint',
30 __PACKAGE__->meta->add_attribute('compiled_type_coercion' => (
31 accessor => '_compiled_type_coercion'
36 my $self = $class->meta->new_object(@_);
37 $self->compile_type_coercion;
41 sub compile_type_coercion {
43 my @coercion_map = @{$self->type_coercion_map};
45 while (@coercion_map) {
46 my ($constraint_name, $action) = splice(@coercion_map, 0, 2);
47 my $type_constraint = ref $constraint_name ? $constraint_name : Moose::Util::TypeConstraints::find_or_parse_type_constraint($constraint_name);
48 (defined $type_constraint)
49 || confess "Could not find the type constraint ($constraint_name) to coerce from";
51 $type_constraint->_compiled_type_constraint,
55 $self->_compiled_type_coercion(sub {
57 foreach my $coercion (@coercions) {
58 my ($constraint, $converter) = @$coercion;
59 if ($constraint->($thing)) {
61 return $converter->($thing);
68 sub has_coercion_for_type {
69 my ($self, $type_name) = @_;
70 my %coercion_map = @{$self->type_coercion_map};
71 exists $coercion_map{$type_name} ? 1 : 0;
74 sub add_type_coercions {
75 my ($self, @new_coercion_map) = @_;
77 my $coercion_map = $self->type_coercion_map;
78 my %has_coercion = @$coercion_map;
80 while (@new_coercion_map) {
81 my ($constraint_name, $action) = splice(@new_coercion_map, 0, 2);
83 confess "A coercion action already exists for '$constraint_name'"
84 if exists $has_coercion{$constraint_name};
86 push @{$coercion_map} => ($constraint_name, $action);
90 $self->compile_type_coercion;
93 sub coerce { $_[0]->_compiled_type_coercion->($_[1]) }
104 Moose::Meta::TypeCoercion - The Moose Type Coercion metaclass
108 For the most part, the only time you will ever encounter an
109 instance of this class is if you are doing some serious deep
110 introspection. This API should not be considered final, but
111 it is B<highly unlikely> that this will matter to a regular
114 If you wish to use features at this depth, please come to the
115 #moose IRC channel on irc.perl.org and we can talk :)
125 =item B<compile_type_coercion>
129 =item B<type_coercion_map>
131 =item B<type_constraint>
133 =item B<has_coercion_for_type>
135 =item B<add_type_coercions>
141 All complex software has bugs lurking in it, and this module is no
142 exception. If you find a bug please either email me, or add the bug
147 Stevan Little E<lt>stevan@iinteractive.comE<gt>
149 =head1 COPYRIGHT AND LICENSE
151 Copyright 2006-2008 by Infinity Interactive, Inc.
153 L<http://www.iinteractive.com>
155 This library is free software; you can redistribute it and/or modify
156 it under the same terms as Perl itself.