| 1 | package DBIx::Class::ResultSet::AccessorsEverywhere; | ||
| 2 | |||
| 3 | # ABSTRACT: Component for DBIx::Class that allows the use of accessor names in search/create/etc | ||
| 4 | |||
| 5 | use 5.010; | ||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | use Carp; | ||
| 9 | no autovivification; | ||
| 10 | |||
| 11 | our $VERSION = '0.10'; | ||
| 12 | |||
| 13 | use parent 'DBIx::Class::ResultSet'; | ||
| 14 | |||
| 15 | # This is certainly buggy. It is just a proof of concept at the moment. I need | ||
| 16 | # to think through conflicting accessor/column names, other methods that need | ||
| 17 | # to be handled, etc. | ||
| 18 | |||
| 19 | sub search { | ||
| 20 | my $self = shift; | ||
| 21 | my $where = shift; | ||
| 22 | |||
| 23 | croak "search expects a hash ref or undef" | ||
| 24 | unless !defined $where | ||
| 25 | or ref $where eq 'HASH'; | ||
| 26 | |||
| 27 | my $new_where = $self->_convert_accessors_to_columns( $where // {} ); | ||
| 28 | return $self->next::method( $new_where, @_ ); | ||
| 29 | } | ||
| 30 | |||
| 31 | sub new_result { | ||
| 32 | my $self = shift; | ||
| 33 | my $attr = shift; | ||
| 34 | |||
| 35 | croak "new_result expects a hash ref or undef" | ||
| 36 | unless !defined $attr | ||
| 37 | or ref $attr eq 'HASH'; | ||
| 38 | |||
| 39 | my $new_attr = $self->_convert_accessors_to_columns( $attr // {} ); | ||
| 40 | return $self->next::method( $new_attr, @_ ); | ||
| 41 | } | ||
| 42 | |||
| 43 | sub find { | ||
| 44 | my $self = shift; | ||
| 45 | my $attr = shift; | ||
| 46 | |||
| 47 | $attr = $self->_convert_accessors_to_columns($attr) if ref $attr eq 'HASH'; | ||
| 48 | return $self->next::method( $attr, @_ ); | ||
| 49 | } | ||
| 50 | |||
| 51 | sub _convert_accessors_to_columns { | ||
| 52 | my ( $self, $orig ) = @_; | ||
| 53 | my $map = $self->_get_accessor_map; | ||
| 54 | |||
| 55 | my $new; | ||
| 56 | my @keys = keys %$orig; | ||
| 57 | for my $key (@keys) { | ||
| 58 | my $new_key = $map->{$key} // $key; | ||
| 59 | my $value = $orig->{$key}; | ||
| 60 | if ( ref $new->{$new_key} eq 'HASH' ) { | ||
| 61 | $value = $self->_convert_accessors_to_columns($value); | ||
| 62 | } | ||
| 63 | $new->{$new_key} = $value; | ||
| 64 | } | ||
| 65 | return $new; | ||
| 66 | } | ||
| 67 | |||
| 68 | sub _get_accessor_map { | ||
| 69 | my $self = shift; | ||
| 70 | |||
| 71 | my $columns_info = $self->result_source->columns_info; | ||
| 72 | my %col_mapping = map { $columns_info->{$_}->{accessor} => $_ } | ||
| 73 | grep { defined $columns_info->{$_}->{accessor} } | ||
| 74 | keys %$columns_info; | ||
| 75 | |||
| 76 | return \%col_mapping; | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; | ||
| 80 | |||
| 81 | __END__ |