97e403193266fddb9d5c36dff3dd679861965f89
[gitmo/MooseX-Types.git] / lib / MooseX / Types / UndefinedType.pm
1 package MooseX::Types::UndefinedType;
2
3 use warnings;
4 use strict;
5
6 use Moose::Util::TypeConstraints ();
7 use Carp::Clan qw( ^MooseX::Types );
8
9 use overload '""'     => sub { shift->name },
10              fallback => 1;
11
12 =head1 DESCRIPTION
13
14 Whenever a type handle function (e.g. C<Int()> can't find a type 
15 constraint under it's full name, it assumes it has not yet been defined.
16 It will then return an instance of this class, handling only 
17 stringification, name and possible identification of undefined types.
18
19 Later, when you try to use the Undefined Type Constraint, autovivification will
20 be attempted.
21
22 =head1 METHODS
23
24 =head2 new
25
26 Takes a full type name as argument and returns an instance of this
27 class.
28
29 =cut
30
31 sub new {
32     return bless { name => $_[1] }, $_[0];
33 }
34
35 =head2 name
36
37 Returns the stored type name.
38
39 =cut
40
41 sub name {
42     return $_[0]->{name};
43 }
44
45 =head2 __autovivify
46
47 Try to see if the type constraint has yet been defined and if so create it.
48
49 =cut
50
51 sub __autovivify {
52     my ($self) = @_;
53     if(my $tc = $self->{instance}) {
54         return $tc;
55     } elsif( my $new_tc = Moose::Util::TypeConstraints::find_type_constraint($self->name)) {
56         $self->{instance} = $new_tc;
57         return $new_tc;
58     } else {
59         return;
60     }
61 }
62
63 =head2 can_be_inlined
64
65 Make sure that if a type hasn't been defined yet when Moose wants to inline it,
66 we don't allow inlining.
67
68 =cut
69
70 sub can_be_inlined {
71     my $self = shift;
72     if(my $type_constraint = $self->__autovivify) {
73         return $type_constraint->can_be_inlined;
74     } else {
75         return;
76     }
77 }
78
79 =head2 AUTOLOAD
80
81 Try to autovivify and delegate
82
83 =cut
84
85 sub AUTOLOAD {
86     my ($self, @args)  = @_;
87     my ($method) = our $AUTOLOAD =~ /([^:]+)$/;    
88
89     if(my $type_constraint = $self->__autovivify) {
90         return $type_constraint->$method(@args);
91     } else {
92         croak "Method '$method' is not supported for " . $self->name;
93     }
94 }
95
96 =head2 DESTROY
97
98 Moose::Meta::TypeConstraint::Parameterizable complains if this isn't here. TODO
99 to find out why.
100
101 =cut
102
103 sub DESTROY {
104     return;
105 }
106
107 =head1 SEE ALSO
108
109 L<MooseX::Types::Moose>,
110 L<Moose::Util::TypeConstraints>, 
111 L<Moose::Meta::TypeConstraint>,
112 L<Carp::Clan>
113
114 =head1 LICENSE
115
116 This program is free software; you can redistribute it and/or modify
117 it under the same terms as perl itself.
118
119 =cut
120
121
122 1;