added strict and warnings to HashRefInflator, fixed inflation for empty has_many...
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultClass / HashRefInflator.pm
1 package DBIx::Class::ResultClass::HashRefInflator;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 DBIx::Class::ResultClass::HashRefInflator
9
10 =head1 SYNOPSIS
11
12  my $rs = $schema->resultset('CD');
13
14  $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
15
16 =head1 DESCRIPTION
17
18 DBIx::Class is not built for speed: it's built for convenience and
19 ease of use. But sometimes you just need to get the data, and skip the
20 fancy objects. That is what this class provides.
21
22 There are two ways of using this class.
23
24 =over
25
26 =item *
27
28 Specify C<< $rs->result_class >> on a specific resultset to affect only that
29 resultset (and any chained off of it); or
30
31 =item *
32
33 Specify C<< __PACKAGE__->result_class >> on your source object to force all
34 uses of that result source to be inflated to hash-refs - this approach is not
35 recommended.
36
37 =back
38
39 =head1 METHODS
40
41 =head2 inflate_result
42
43 Inflates the result and prefetched data into a hash-ref using L<mk_hash>.
44
45 =cut
46
47 sub inflate_result {
48     my ($self, $source, $me, $prefetch) = @_;
49
50     return mk_hash($me, $prefetch);
51 }
52
53 =head2 mk_hash
54
55 This does all the work of inflating the (pre)fetched data.
56
57 =cut
58
59 sub mk_hash {
60     my ($me, $rest) = @_;
61
62     # $me is the hashref of cols/data from the immediate resultsource
63     # $rest is a deep hashref of all the data from the prefetched
64     # related sources.
65
66     # to avoid emtpy has_many rels contain one empty hashref
67     return undef if (not keys %$me);
68
69     my $def;
70
71     foreach (values %$me) {
72         if (defined $_) {
73             $def = 1;
74             last;
75         }
76     }
77     return undef unless $def;
78
79     return { %$me,
80         map {
81           ( $_ =>
82              ref($rest->{$_}[0]) eq 'ARRAY'
83                  ? [ grep defined, map mk_hash(@$_), @{$rest->{$_}} ]
84                  : mk_hash( @{$rest->{$_}} )
85           )
86         } keys %$rest
87     };
88 }
89
90 1;