0e02d6dee67695a31806854f6e68829b7f7815ab
[gitmo/Moose.git] / lib / Moose / Meta / TypeCoercion / Union.pm
1
2 package Moose::Meta::TypeCoercion::Union;
3
4 use strict;
5 use warnings;
6 use metaclass;
7
8 use Scalar::Util 'blessed';
9
10 our $AUTHORITY = 'cpan:STEVAN';
11
12 use base 'Moose::Meta::TypeCoercion';
13
14 sub compile_type_coercion {
15     my $self            = shift;
16     my $type_constraint = $self->type_constraint;
17
18     (blessed $type_constraint && $type_constraint->isa('Moose::Meta::TypeConstraint::Union'))
19      || Moose->throw_error("You can only create a Moose::Meta::TypeCoercion::Union for a " .
20                 "Moose::Meta::TypeConstraint::Union, not a $type_constraint");
21
22     $self->_compiled_type_coercion(
23         sub {
24             my $value = shift;
25
26             foreach my $type ( grep { $_->has_coercion }
27                 @{ $type_constraint->type_constraints } ) {
28                 my $temp = $type->coerce($value);
29                 return $temp if $type_constraint->check($temp);
30             }
31
32             return $value;
33         }
34     );
35 }
36
37 sub has_coercion_for_type { 0 }
38
39 sub add_type_coercions {
40     require Moose;
41     Moose->throw_error("Cannot add additional type coercions to Union types");
42 }
43
44 1;
45
46 # ABSTRACT: The Moose Type Coercion metaclass for Unions
47
48 __END__
49
50 =pod
51
52 =head1 DESCRIPTION
53
54 This is a subclass of L<Moose::Meta::TypeCoercion> that is used for
55 L<Moose::Meta::TypeConstraint::Union> objects.
56 =head1 METHODS
57
58 =over 4
59
60 =item B<< $coercion->has_coercion_for_type >>
61
62 This method always returns false.
63
64 =item B<< $coercion->add_type_coercions >>
65
66 This method always throws an error. You cannot add coercions to a
67 union type coercion.
68
69 =item B<< $coercion->coerce($value) >>
70
71 This method will coerce by trying the coercions for each type in the
72 union.
73
74 =back
75
76 =head1 BUGS
77
78 See L<Moose/BUGS> for details on reporting bugs.
79
80 =cut