429b6f9f33bddb10f0a99039395c9fcc31cb0de3
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
1 package Mouse::Meta::Attribute;
2 use strict;
3 use warnings;
4
5 use Mouse::Util;
6
7 use Mouse::Meta::TypeConstraint;
8 use Mouse::Meta::Method::Accessor;
9
10 sub new {
11     my ($class, $name, %options) = @_;
12
13     $options{name} = $name;
14
15     $options{init_arg} = $name
16         unless exists $options{init_arg};
17
18     my $is = $options{is} ||= '';
19
20     if($is eq 'rw'){
21         $options{accessor} = $name if !exists $options{accessor};
22     }
23     elsif($is eq 'ro'){
24         $options{reader}   = $name if !exists $options{reader};
25     }
26
27     bless \%options, $class;
28 }
29
30 # readers
31
32 sub name                 { $_[0]->{name}                   }
33 sub associated_class     { $_[0]->{associated_class}       }
34
35 sub accessor             { $_[0]->{accessor}               }
36 sub reader               { $_[0]->{reader}                 }
37 sub writer               { $_[0]->{writer}                 }
38 sub predicate            { $_[0]->{predicate}              }
39 sub clearer              { $_[0]->{clearer}                }
40 sub handles              { $_[0]->{handles}                }
41
42 sub _is_metadata         { $_[0]->{is}                     }
43 sub is_required          { $_[0]->{required}               }
44 sub default              { $_[0]->{default}                }
45 sub is_lazy              { $_[0]->{lazy}                   }
46 sub is_lazy_build        { $_[0]->{lazy_build}             }
47 sub is_weak_ref          { $_[0]->{weak_ref}               }
48 sub init_arg             { $_[0]->{init_arg}               }
49 sub type_constraint      { $_[0]->{type_constraint}        }
50 sub find_type_constraint {
51     Carp::carp("This method was deprecated");
52     $_[0]->type_constraint();
53 }
54 sub trigger              { $_[0]->{trigger}                }
55 sub builder              { $_[0]->{builder}                }
56 sub should_auto_deref    { $_[0]->{auto_deref}             }
57 sub should_coerce        { $_[0]->{should_coerce}          }
58
59 # predicates
60
61 sub has_accessor         { exists $_[0]->{accessor}        }
62 sub has_reader           { exists $_[0]->{reader}          }
63 sub has_writer           { exists $_[0]->{writer}          }
64 sub has_predicate        { exists $_[0]->{predicate}       }
65 sub has_clearer          { exists $_[0]->{clearer}         }
66 sub has_handles          { exists $_[0]->{handles}         }
67
68 sub has_default          { exists $_[0]->{default}         }
69 sub has_type_constraint  { exists $_[0]->{type_constraint} }
70 sub has_trigger          { exists $_[0]->{trigger}         }
71 sub has_builder          { exists $_[0]->{builder}         }
72
73 sub _create_args {
74     $_[0]->{_create_args} = $_[1] if @_ > 1;
75     $_[0]->{_create_args}
76 }
77
78 sub accessor_metaclass { 'Mouse::Meta::Method::Accessor' }
79
80 sub create {
81     my ($self, $class, $name, %args) = @_;
82
83     $args{name}             = $name;
84     $args{associated_class} = $class;
85
86     %args = $self->canonicalize_args($name, %args);
87     $self->validate_args($name, \%args);
88
89     $args{should_coerce} = delete $args{coerce}
90         if exists $args{coerce};
91
92     if (exists $args{isa}) {
93         my $type_constraint = delete $args{isa};
94         $args{type_constraint}= Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($type_constraint);
95     }
96
97     my $attribute = $self->new($name, %args);
98
99     $attribute->_create_args(\%args);
100
101     $class->add_attribute($attribute);
102
103     my $associated_methods = 0;
104
105     my $generator_class = $self->accessor_metaclass;
106     foreach my $type(qw(accessor reader writer predicate clearer handles)){
107         if(exists $attribute->{$type}){
108             my $installer    = '_install_' . $type;
109             $generator_class->$installer($attribute, $attribute->{$type}, $class);
110             $associated_methods++;
111         }
112     }
113
114     if($associated_methods == 0 && ($attribute->_is_metadata || '') ne 'bare'){
115         Carp::cluck(qq{Attribute ($name) of class }.$class->name.qq{ has no associated methods (did you mean to provide an "is" argument?)});
116
117     }
118
119     return $attribute;
120 }
121
122 sub canonicalize_args {
123     my $self = shift;
124     my $name = shift;
125     my %args = @_;
126
127     if ($args{lazy_build}) {
128         $args{lazy}      = 1;
129         $args{required}  = 1;
130         $args{builder}   = "_build_${name}"
131             if !exists($args{builder});
132         if ($name =~ /^_/) {
133             $args{clearer}   = "_clear${name}" if !exists($args{clearer});
134             $args{predicate} = "_has${name}" if !exists($args{predicate});
135         }
136         else {
137             $args{clearer}   = "clear_${name}" if !exists($args{clearer});
138             $args{predicate} = "has_${name}" if !exists($args{predicate});
139         }
140     }
141
142     return %args;
143 }
144
145 sub validate_args {
146     my $self = shift;
147     my $name = shift;
148     my $args = shift;
149
150     $self->throw_error("You can not use lazy_build and default for the same attribute ($name)")
151         if $args->{lazy_build} && exists $args->{default};
152
153     $self->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it")
154         if $args->{lazy}
155         && !exists($args->{default})
156         && !exists($args->{builder});
157
158     $self->throw_error("References are not allowed as default values, you must wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
159         if ref($args->{default})
160         && ref($args->{default}) ne 'CODE';
161
162     $self->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)")
163         if $args->{auto_deref} && !exists($args->{isa});
164
165     $self->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)")
166         if $args->{auto_deref}
167         && $args->{isa} !~ /^(?:ArrayRef|HashRef)(?:\[.*\])?$/;
168
169     if ($args->{trigger}) {
170         if (ref($args->{trigger}) eq 'HASH') {
171             $self->throw_error("HASH-based form of trigger has been removed. Only the coderef form of triggers are now supported.");
172         }
173
174         $self->throw_error("Trigger must be a CODE ref on attribute ($name)")
175             if ref($args->{trigger}) ne 'CODE';
176     }
177
178     return 1;
179 }
180
181 sub verify_against_type_constraint {
182     my ($self, $value) = @_;
183     my $tc = $self->type_constraint;
184     return 1 unless $tc;
185
186     local $_ = $value;
187     return 1 if $tc->check($value);
188
189     $self->verify_type_constraint_error($self->name, $value, $tc);
190 }
191
192 sub verify_type_constraint_error {
193     my($self, $name, $value, $type) = @_;
194     $self->throw_error("Attribute ($name) does not pass the type constraint because: " . $type->get_message($value));
195 }
196
197 sub coerce_constraint { ## my($self, $value) = @_;
198     my $type = $_[0]->{type_constraint}
199         or return $_[1];
200     return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $_[0]->type_constraint, $_[1]);
201 }
202
203 sub _canonicalize_handles {
204     my $self    = shift;
205     my $handles = shift;
206
207     if (ref($handles) eq 'HASH') {
208         return %$handles;
209     }
210     elsif (ref($handles) eq 'ARRAY') {
211         return map { $_ => $_ } @$handles;
212     }
213     else {
214         $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
215     }
216 }
217
218 sub clone_parent {
219     my $self  = shift;
220     my $class = shift;
221     my $name  = shift;
222     my %args  = ($self->get_parent_args($class, $name), @_);
223
224     $self->create($class, $name, %args);
225 }
226
227 sub get_parent_args {
228     my $self  = shift;
229     my $class = shift;
230     my $name  = shift;
231
232     for my $super ($class->linearized_isa) {
233         my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
234             or next;
235         return %{ $super_attr->_create_args };
236     }
237
238     $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
239 }
240
241 sub throw_error{
242     my $self = shift;
243
244     my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
245     $metaclass->throw_error(@_, depth => 1);
246 }
247
248 1;
249
250 __END__
251
252 =head1 NAME
253
254 Mouse::Meta::Attribute - attribute metaclass
255
256 =head1 METHODS
257
258 =head2 new %args -> Mouse::Meta::Attribute
259
260 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
261
262 =head2 create OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
263
264 Creates a new attribute in OwnerClass. Accessors and helper methods are
265 installed. Some error checking is done.
266
267 =head2 name -> AttributeName
268
269 =head2 associated_class -> OwnerClass
270
271 =head2 is_required -> Bool
272
273 =head2 default -> Item
274
275 =head2 has_default -> Bool
276
277 =head2 is_lazy -> Bool
278
279 =head2 predicate -> MethodName | Undef
280
281 =head2 has_predicate -> Bool
282
283 =head2 clearer -> MethodName | Undef
284
285 =head2 has_clearer -> Bool
286
287 =head2 handles -> { LocalName => RemoteName }
288
289 =head2 has_handles -> Bool
290
291 =head2 is_weak_ref -> Bool
292
293 =head2 init_arg -> Str
294
295 =head2 type_constraint -> Str
296
297 =head2 has_type_constraint -> Bool
298
299 =head2 trigger => CODE | Undef
300
301 =head2 has_trigger -> Bool
302
303 =head2 builder => MethodName | Undef
304
305 =head2 has_builder -> Bool
306
307 =head2 is_lazy_build => Bool
308
309 =head2 should_auto_deref -> Bool
310
311 Informational methods.
312
313 =head2 verify_against_type_constraint Item -> 1 | ERROR
314
315 Checks that the given value passes this attribute's type constraint. Returns 1
316 on success, otherwise C<confess>es.
317
318 =head2 canonicalize_args Name, %args -> %args
319
320 Canonicalizes some arguments to create. In particular, C<lazy_build> is
321 canonicalized into C<lazy>, C<builder>, etc.
322
323 =head2 validate_args Name, \%args -> 1 | ERROR
324
325 Checks that the arguments to create the attribute (ie those specified by
326 C<has>) are valid.
327
328 =head2 clone_parent OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
329
330 Creates a new attribute in OwnerClass, inheriting options from parent classes.
331 Accessors and helper methods are installed. Some error checking is done.
332
333 =head2 get_parent_args OwnerClass, AttributeName -> Hash
334
335 Returns the options that the parent class of C<OwnerClass> used for attribute
336 C<AttributeName>.
337
338 =cut
339