somehow i messed up the merge. this fixes it
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / Accessor.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::Accessor;
3
4 use strict;
5 use warnings;
6 use Sub::Name ();
7 use Class::Inspector ();
8
9 sub register_relationship {
10   my ($class, $rel, $info) = @_;
11   if (my $acc_type = $info->{attrs}{accessor}) {
12     $class->add_relationship_accessor($rel => $acc_type);
13   }
14   $class->next::method($rel => $info);
15 }
16
17 sub add_relationship_accessor {
18   my ($class, $rel, $acc_type) = @_;
19   my %meth;
20   if ($acc_type eq 'single') {
21     my $rel_info = $class->relationship_info($rel);
22     $meth{$rel} = sub {
23       my $self = shift;
24       if (@_) {
25         $self->set_from_related($rel, @_);
26         return $self->{_relationship_data}{$rel} = $_[0];
27       } elsif (exists $self->{_relationship_data}{$rel}) {
28         return $self->{_relationship_data}{$rel};
29       } else {
30         my $cond = $self->result_source->resolve_condition(
31           $rel_info->{cond}, $rel, $self
32         );
33         if ($rel_info->{attrs}->{undef_on_null_fk}){
34           return if grep { not defined } values %$cond;
35         }
36         my $val = $self->find_related($rel, {}, {});
37         return unless $val;
38         return $self->{_relationship_data}{$rel} = $val;
39       }
40     };
41   } elsif ($acc_type eq 'filter') {
42     $class->throw_exception("No such column $rel to filter")
43        unless $class->has_column($rel);
44     my $f_class = $class->relationship_info($rel)->{class};
45     $class->inflate_column($rel,
46       { inflate => sub {
47           my ($val, $self) = @_;
48           return $self->find_or_new_related($rel, {}, {});
49         },
50         deflate => sub {
51           my ($val, $self) = @_;
52           $self->throw_exception("$val isn't a $f_class") unless $val->isa($f_class);
53           return ($val->_ident_values)[0];
54             # WARNING: probably breaks for multi-pri sometimes. FIXME
55         }
56       }
57     );
58   } elsif ($acc_type eq 'multi') {
59     $meth{$rel} = sub { shift->search_related($rel, @_) };
60     $meth{"${rel}_rs"} = sub { shift->search_related_rs($rel, @_) };
61     $meth{"add_to_${rel}"} = sub { shift->create_related($rel, @_); };
62   } else {
63     $class->throw_exception("No such relationship accessor type $acc_type");
64   }
65   {
66     no strict 'refs';
67     no warnings 'redefine';
68     foreach my $meth (keys %meth) {
69       my $name = join '::', $class, $meth;
70       *$name = Sub::Name::subname($name, $meth{$meth});
71     }
72   }
73 }
74
75 1;