2 package Moose::Meta::Attribute;
7 use Scalar::Util 'blessed', 'weaken', 'reftype';
11 our $VERSION = '0.12';
12 our $AUTHORITY = 'cpan:STEVAN';
14 use Moose::Meta::Method::Accessor;
15 use Moose::Util::TypeConstraints ();
17 use base 'Class::MOP::Attribute';
19 # options which are not directly used
20 # but we store them for metadata purposes
21 __PACKAGE__->meta->add_attribute('isa' => (reader => '_isa_metadata'));
22 __PACKAGE__->meta->add_attribute('does' => (reader => '_does_metadata'));
23 __PACKAGE__->meta->add_attribute('is' => (reader => '_is_metadata'));
25 # these are actual options for the attrs
26 __PACKAGE__->meta->add_attribute('required' => (reader => 'is_required' ));
27 __PACKAGE__->meta->add_attribute('lazy' => (reader => 'is_lazy' ));
28 __PACKAGE__->meta->add_attribute('coerce' => (reader => 'should_coerce' ));
29 __PACKAGE__->meta->add_attribute('weak_ref' => (reader => 'is_weak_ref' ));
30 __PACKAGE__->meta->add_attribute('auto_deref' => (reader => 'should_auto_deref'));
31 __PACKAGE__->meta->add_attribute('type_constraint' => (
32 reader => 'type_constraint',
33 predicate => 'has_type_constraint',
35 __PACKAGE__->meta->add_attribute('trigger' => (
37 predicate => 'has_trigger',
39 __PACKAGE__->meta->add_attribute('handles' => (
41 predicate => 'has_handles',
43 __PACKAGE__->meta->add_attribute('documentation' => (
44 reader => 'documentation',
45 predicate => 'has_documentation',
49 my ($class, $name, %options) = @_;
50 $class->_process_options($name, \%options);
51 return $class->SUPER::new($name, %options);
54 sub clone_and_inherit_options {
55 my ($self, %options) = @_;
56 # you can change default, required, coerce, documentation and lazy
58 foreach my $legal_option (qw(default coerce required documentation lazy)) {
59 if (exists $options{$legal_option}) {
60 $actual_options{$legal_option} = $options{$legal_option};
61 delete $options{$legal_option};
65 # handles can only be added, not changed
66 if ($options{handles}) {
67 confess "You can only add the 'handles' option, you cannot change it"
68 if $self->has_handles;
69 $actual_options{handles} = $options{handles};
70 delete $options{handles};
73 # isa can be changed, but only if the
74 # new type is a subtype
77 if (blessed($options{isa}) && $options{isa}->isa('Moose::Meta::TypeConstraint')) {
78 $type_constraint = $options{isa};
81 $type_constraint = Moose::Util::TypeConstraints::find_type_constraint($options{isa});
82 (defined $type_constraint)
83 || confess "Could not find the type constraint '" . $options{isa} . "'";
86 # check here to see if the new type
87 # is a subtype of the old one
88 ($type_constraint->is_subtype_of($self->type_constraint->name))
89 || confess "New type constraint setting must be a subtype of inherited one"
90 # iff we have a type constraint that is ...
91 if $self->has_type_constraint;
93 $actual_options{type_constraint} = $type_constraint;
96 (scalar keys %options == 0)
97 || confess "Illegal inherited options => (" . (join ', ' => keys %options) . ")";
98 $self->clone(%actual_options);
101 sub _process_options {
102 my ($class, $name, $options) = @_;
104 if (exists $options->{is}) {
105 if ($options->{is} eq 'ro') {
106 $options->{reader} ||= $name;
107 (!exists $options->{trigger})
108 || confess "Cannot have a trigger on a read-only attribute";
110 elsif ($options->{is} eq 'rw') {
111 $options->{accessor} = $name;
112 ((reftype($options->{trigger}) || '') eq 'CODE')
113 || confess "Trigger must be a CODE ref"
114 if exists $options->{trigger};
117 confess "I do not understand this option (is => " . $options->{is} . ")"
121 if (exists $options->{isa}) {
123 if (exists $options->{does}) {
124 if (eval { $options->{isa}->can('does') }) {
125 ($options->{isa}->does($options->{does}))
126 || confess "Cannot have an isa option and a does option if the isa does not do the does";
129 confess "Cannot have an isa option which cannot ->does()";
133 # allow for anon-subtypes here ...
134 if (blessed($options->{isa}) && $options->{isa}->isa('Moose::Meta::TypeConstraint')) {
135 $options->{type_constraint} = $options->{isa};
138 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_type_constraint(
140 parent => Moose::Util::TypeConstraints::find_type_constraint('Object'),
141 constraint => sub { $_[0]->isa($options->{isa}) }
146 elsif (exists $options->{does}) {
147 # allow for anon-subtypes here ...
148 if (blessed($options->{does}) && $options->{does}->isa('Moose::Meta::TypeConstraint')) {
149 $options->{type_constraint} = $options->{isa};
152 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_type_constraint(
153 $options->{does} => {
154 parent => Moose::Util::TypeConstraints::find_type_constraint('Role'),
155 constraint => sub { $_[0]->does($options->{does}) }
161 if (exists $options->{coerce} && $options->{coerce}) {
162 (exists $options->{type_constraint})
163 || confess "You cannot have coercion without specifying a type constraint";
164 confess "You cannot have a weak reference to a coerced value"
165 if $options->{weak_ref};
168 if (exists $options->{auto_deref} && $options->{auto_deref}) {
169 (exists $options->{type_constraint})
170 || confess "You cannot auto-dereference without specifying a type constraint";
171 ($options->{type_constraint}->is_a_type_of('ArrayRef') ||
172 $options->{type_constraint}->is_a_type_of('HashRef'))
173 || confess "You cannot auto-dereference anything other than a ArrayRef or HashRef";
176 if (exists $options->{lazy} && $options->{lazy}) {
177 (exists $options->{default})
178 || confess "You cannot have lazy attribute without specifying a default value for it";
182 sub initialize_instance_slot {
183 my ($self, $meta_instance, $instance, $params) = @_;
184 my $init_arg = $self->init_arg();
185 # try to fetch the init arg from the %params ...
188 if (exists $params->{$init_arg}) {
189 $val = $params->{$init_arg};
191 if (!defined $val && $self->is_required) {
192 confess "Attribute (" . $self->name . ") is required and cannot be undef";
196 # skip it if it's lazy
197 return if $self->is_lazy;
198 # and die if it's required and doesn't have a default value
199 confess "Attribute (" . $self->name . ") is required"
200 if $self->is_required && !$self->has_default;
203 # if nothing was in the %params, we can use the
204 # attribute's default value (if it has one)
205 if (!defined $val && $self->has_default) {
206 $val = $self->default($instance);
209 if (defined $val || $self->has_default) {
210 if ($self->has_type_constraint) {
211 my $type_constraint = $self->type_constraint;
212 if ($self->should_coerce && $type_constraint->has_coercion) {
213 $val = $type_constraint->coerce($val);
215 (defined($type_constraint->check($val)))
216 || confess "Attribute (" .
218 ") does not pass the type constraint (" .
219 $type_constraint->name .
222 ? (blessed($val) && overload::Overloaded($val)
223 ? overload::StrVal($val)
230 $meta_instance->set_slot_value($instance, $self->name, $val);
231 $meta_instance->weaken_slot_value($instance, $self->name)
232 if ref $val && $self->is_weak_ref;
238 my ($self, $instance, $value) = @_;
240 my $attr_name = $self->name;
242 if ($self->is_required) {
244 || confess "Attribute ($attr_name) is required, so cannot be set to undef";
247 if ($self->has_type_constraint) {
249 my $type_constraint = $self->type_constraint;
251 if ($self->should_coerce) {
252 $value = $type_constraint->coerce($value);
254 defined($type_constraint->_compiled_type_constraint->($value))
255 || confess "Attribute ($attr_name) does not pass the type constraint ("
256 . $type_constraint->name
260 (blessed($value) && overload::Overloaded($value)
261 ? overload::StrVal($value)
268 my $meta_instance = Class::MOP::Class->initialize(blessed($instance))
271 $meta_instance->set_slot_value($instance, $attr_name, $value);
273 if (ref $value && $self->is_weak_ref) {
274 $meta_instance->weaken_slot_value($instance, $attr_name);
277 if ($self->has_trigger) {
278 $self->trigger->($instance, $value, $self);
283 my ($self, $instance) = @_;
285 if ($self->is_lazy) {
286 unless ($self->has_value($instance)) {
287 if ($self->has_default) {
288 my $default = $self->default($instance);
289 $self->set_value($instance, $default);
292 $self->set_value($instance, undef);
297 if ($self->should_auto_deref) {
299 my $type_constraint = $self->type_constraint;
301 if ($type_constraint->is_a_type_of('ArrayRef')) {
302 my $rv = $self->SUPER::get_value($instance);
303 return unless defined $rv;
304 return wantarray ? @{ $rv } : $rv;
306 elsif ($type_constraint->is_a_type_of('HashRef')) {
307 my $rv = $self->SUPER::get_value($instance);
308 return unless defined $rv;
309 return wantarray ? %{ $rv } : $rv;
312 confess "Can not auto de-reference the type constraint '" . $type_constraint->name . "'";
318 return $self->SUPER::get_value($instance);
322 ## installing accessors
324 sub accessor_metaclass { 'Moose::Meta::Method::Accessor' }
326 sub install_accessors {
328 $self->SUPER::install_accessors(@_);
330 if ($self->has_handles) {
333 # Here we canonicalize the 'handles' option
334 # this will sort out any details and always
335 # return an hash of methods which we want
336 # to delagate to, see that method for details
337 my %handles = $self->_canonicalize_handles();
339 # find the name of the accessor for this attribute
340 my $accessor_name = $self->reader || $self->accessor;
341 (defined $accessor_name)
342 || confess "You cannot install delegation without a reader or accessor for the attribute";
344 # make sure we handle HASH accessors correctly
345 ($accessor_name) = keys %{$accessor_name}
346 if ref($accessor_name) eq 'HASH';
348 # install the delegation ...
349 my $associated_class = $self->associated_class;
350 foreach my $handle (keys %handles) {
351 my $method_to_call = $handles{$handle};
353 (!$associated_class->has_method($handle))
354 || confess "You cannot overwrite a locally defined method ($handle) with a delegation";
357 # handles is not allowed to delegate
358 # any of these methods, as they will
359 # override the ones in your class, which
360 # is almost certainly not what you want.
361 next if $handle =~ /^BUILD|DEMOLISH$/ || Moose::Object->can($handle);
363 if ((reftype($method_to_call) || '') eq 'CODE') {
364 $associated_class->add_method($handle => $method_to_call);
367 $associated_class->add_method($handle => sub {
369 # we should check for lack of
370 # a callable return value from
372 my $proxy = (shift)->$accessor_name();
374 goto &{ $proxy->can($method_to_call)};
383 # private methods to help delegation ...
385 sub _canonicalize_handles {
387 my $handles = $self->handles;
388 if (my $handle_type = ref($handles)) {
389 if ($handle_type eq 'HASH') {
392 elsif ($handle_type eq 'ARRAY') {
393 return map { $_ => $_ } @{$handles};
395 elsif ($handle_type eq 'Regexp') {
396 ($self->has_type_constraint)
397 || confess "Cannot delegate methods based on a RegExpr without a type constraint (isa)";
398 return map { ($_ => $_) }
399 grep { /$handles/ } $self->_get_delegate_method_list;
401 elsif ($handle_type eq 'CODE') {
402 return $handles->($self, $self->_find_delegate_metaclass);
405 confess "Unable to canonicalize the 'handles' option with $handles";
409 my $role_meta = eval { $handles->meta };
411 confess "Unable to canonicalize the 'handles' option with $handles because : $@";
414 (blessed $role_meta && $role_meta->isa('Moose::Meta::Role'))
415 || confess "Unable to canonicalize the 'handles' option with $handles because ->meta is not a Moose::Meta::Role";
417 return map { $_ => $_ } (
418 $role_meta->get_method_list,
419 $role_meta->get_required_method_list
424 sub _find_delegate_metaclass {
426 if (my $class = $self->_isa_metadata) {
427 # if the class does have
428 # a meta method, use it
429 return $class->meta if $class->can('meta');
430 # otherwise we might be
431 # dealing with a non-Moose
432 # class, and need to make
434 return Moose::Meta::Class->initialize($class);
436 elsif (my $role = $self->_does_metadata) {
437 # our role will always have
442 confess "Cannot find delegate metaclass for attribute " . $self->name;
446 sub _get_delegate_method_list {
448 my $meta = $self->_find_delegate_metaclass;
449 if ($meta->isa('Class::MOP::Class')) {
450 return map { $_->{name} } # NOTE: !never! delegate &meta
451 grep { $_->{class} ne 'Moose::Object' && $_->{name} ne 'meta' }
452 $meta->compute_all_applicable_methods;
454 elsif ($meta->isa('Moose::Meta::Role')) {
455 return $meta->get_method_list;
458 confess "Unable to recognize the delegate metaclass '$meta'";
470 Moose::Meta::Attribute - The Moose attribute metaclass
474 This is a subclass of L<Class::MOP::Attribute> with Moose specific
477 For the most part, the only time you will ever encounter an
478 instance of this class is if you are doing some serious deep
479 introspection. To really understand this class, you need to refer
480 to the L<Class::MOP::Attribute> documentation.
484 =head2 Overridden methods
486 These methods override methods in L<Class::MOP::Attribute> and add
487 Moose specific features. You can safely assume though that they
488 will behave just as L<Class::MOP::Attribute> does.
494 =item B<initialize_instance_slot>
496 =item B<install_accessors>
498 =item B<accessor_metaclass>
504 eval { $point->meta->get_attribute('x')->set_value($point, 'fourty-two') };
509 I<Attribute (x) does not pass the type constraint (Int) with 'fourty-two'>
511 Before setting the value, a check is made on the type constraint of
512 the attribute, if it has one, to see if the value passes it. If the
513 value fails to pass, the set operation dies with a L<Carp/confess>.
515 Any coercion to convert values is done before checking the type constraint.
517 To check a value against a type constraint before setting it, fetch the
518 attribute instance using L<Moose::Meta::Attribute/find_attribute_by_name>,
519 fetch the type_constraint from the attribute using L<Moose::Meta::Attribute/type_constraint>
520 and call L<Moose::Meta::TypeConstraint/check>. See L<Moose::Cookbook::RecipeX>
525 =head2 Additional Moose features
527 Moose attributes support type-constraint checking, weak reference
528 creation and type coercion.
532 =item B<clone_and_inherit_options>
534 This is to support the C<has '+foo'> feature, it clones an attribute
535 from a superclass and allows a very specific set of changes to be made
538 =item B<has_type_constraint>
540 Returns true if this meta-attribute has a type constraint.
542 =item B<type_constraint>
544 A read-only accessor for this meta-attribute's type constraint. For
545 more information on what you can do with this, see the documentation
546 for L<Moose::Meta::TypeConstraint>.
550 Returns true if this meta-attribute performs delegation.
554 This returns the value which was passed into the handles option.
558 Returns true if this meta-attribute produces a weak reference.
562 Returns true if this meta-attribute is required to have a value.
566 Returns true if this meta-attribute should be initialized lazily.
568 NOTE: lazy attributes, B<must> have a C<default> field set.
570 =item B<should_coerce>
572 Returns true if this meta-attribute should perform type coercion.
574 =item B<should_auto_deref>
576 Returns true if this meta-attribute should perform automatic
579 NOTE: This can only be done for attributes whose type constraint is
580 either I<ArrayRef> or I<HashRef>.
584 Returns true if this meta-attribute has a trigger set.
588 This is a CODE reference which will be executed every time the
589 value of an attribute is assigned. The CODE ref will get two values,
590 the invocant and the new value. This can be used to handle I<basic>
591 bi-directional relations.
593 =item B<documentation>
595 This is a string which contains the documentation for this attribute.
596 It serves no direct purpose right now, but it might in the future
597 in some kind of automated documentation system perhaps.
599 =item B<has_documentation>
601 Returns true if this meta-attribute has any documentation.
607 All complex software has bugs lurking in it, and this module is no
608 exception. If you find a bug please either email me, or add the bug
613 Stevan Little E<lt>stevan@iinteractive.comE<gt>
615 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
617 =head1 COPYRIGHT AND LICENSE
619 Copyright 2006, 2007 by Infinity Interactive, Inc.
621 L<http://www.iinteractive.com>
623 This library is free software; you can redistribute it and/or modify
624 it under the same terms as Perl itself.