Handle all ways of getting arrays at the leaves
authorMike Rylander <mrylander@gmail.com>
Mon, 26 Mar 2012 14:32:43 +0000 (10:32 -0400)
committerMike Rylander <mrylander@gmail.com>
Mon, 26 Mar 2012 14:40:07 +0000 (10:40 -0400)
We can get arrays of values be either:
 - ending on a $field within a has_many reltype
 - passing through a path that is a has_many reltype

This detects either and array-ifies the value on the flat row.

Signed-off-by: Mike Rylander <mrylander@gmail.com>
Open-ILS/src/perlmods/lib/OpenILS/Application/Flattener.pm

index 73d73be..a6c77d3 100644 (file)
@@ -365,21 +365,37 @@ sub process_result {
         my @path = @{ $mapping->{path} };
         my $field = pop @path;
 
-        my $obj = $fmobj;
+        my $objs = [$fmobj];
         while (my $step = shift @path) {
-            $obj = $obj->$step;
-            last unless ref $obj;
+            $objs = [ map { $_->$step } @$objs ];
+            last unless ref $$objs[0];
         }
 
-        if (ref $obj eq 'ARRAY') {
-            # might_have links return arrays
-            $flatrow->{$key} = [ map {$_->$field} @$obj ];
+        # We can get arrays of values be either:
+        #  - ending on a $field within a has_many reltype
+        #  - passing through a path that is a has_many reltype
+        if (@$objs > 1 or ref $$objs[0] eq 'ARRAY') {
+            $flatrow->{$key} = [];
+            for my $o (@$objs) {
+                push @{ $flatrow->{$key} }, extract_field_value( $o, $field );
+            }
         } else {
-            $flatrow->{$key} = ref $obj ? $obj->$field : undef;
+            $flatrow->{$key} = extract_field_value( $$objs[0], $field );
         }
     }
 
     return $flatrow;
 }
 
+sub extract_field_value {
+    my $obj = shift;
+    my $field = shift;
+
+    if (ref $obj eq 'ARRAY') {
+        # has_many links return arrays
+        return ( map {$_->$field} @$obj );
+    }
+    return ref $obj ? $obj->$field : undef;
+}
+
 1;