I hate you all.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / ManyToMany.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::ManyToMany;
3
4 use strict;
5 use warnings;
6
7 sub many_to_many {
8   my ($class, $meth, $rel, $f_rel, $rel_attrs) = @_;
9   {
10     no strict 'refs';
11     no warnings 'redefine';
12
13     my $add_meth = "add_to_${meth}";
14     my $remove_meth = "remove_from_${meth}";
15     my $set_meth = "set_${meth}";
16
17     $rel_attrs->{alias} ||= $f_rel;
18
19     *{"${class}::${meth}"} = sub {
20       my $self = shift;
21       my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
22       my @args = ($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
23       $self->search_related($rel)->search_related(
24         $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
25       );
26     };
27
28     *{"${class}::${add_meth}"} = sub {
29       my $self = shift;
30       @_ > 0 or $self->throw_exception(
31         "${add_meth} needs an object or hashref"
32       );
33       my $source = $self->result_source;
34       my $schema = $source->schema;
35       my $rel_source_name = $source->relationship_info($rel)->{source};
36       my $rel_source = $schema->resultset($rel_source_name)->result_source;
37       my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
38       my $f_rel_rs = $schema->resultset($f_rel_source_name)->search({}, $rel_attrs||{});
39
40       my $obj;
41       if (ref $_[0]) {
42         if (ref $_[0] eq 'HASH') {
43           $obj = $f_rel_rs->create($_[0]);
44         } else {
45           $obj = $_[0];
46         }
47       } else {
48         $obj = $f_rel_rs->create({@_});
49       }
50
51       my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
52       my $link = $self->search_related($rel)->new_result({});
53       $link->set_from_related($f_rel, $obj);
54       $link->set_columns($link_vals);
55       $link->insert();
56     };
57
58     *{"${class}::${set_meth}"} = sub {
59       my $self = shift;
60       @_ > 0 or $self->throw_exception(
61         "{$set_meth} needs a list of objects or hashrefs"
62       );
63       my @to_set = (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_);
64       $self->search_related($rel, {})->delete;
65       $self->$add_meth($_) for (@to_set);
66     };
67
68     *{"${class}::${remove_meth}"} = sub {
69       my $self = shift;
70       @_ > 0 && ref $_[0] ne 'HASH'
71         or $self->throw_exception("${remove_meth} needs an object");
72       my $obj = shift;
73       my $rel_source = $self->search_related($rel)->result_source;
74       my $cond = $rel_source->relationship_info($f_rel)->{cond};
75       my $link_cond = $rel_source->resolve_condition(
76         $cond, $obj, $f_rel
77       );
78       $self->search_related($rel, $link_cond)->delete;
79     };
80
81   }
82 }
83
84 1;