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