From 58356c12bbaf4dc7eb3f7c918b62f91606062761 Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Tue, 28 Jan 2020 16:24:51 -0300 Subject: [PATCH] Bug 24528: Add *_count support to to_api This patch adds a way to tell to_api an attribute needs to be calculated as the count on an existing method/relationship result. For example, if we wanted to include the holds_count attribute for a Koha::Patron object, we would call it: $ patron_json = $patron->to_api({ embed => { holds_count => { is_count => 1 } } }); This way to_api will internally call $json->{holds_count} = $self->holds->count; To test: 1. Apply the tests patch 2. Run: $ kshell k$ prove t/db_dependent/Koha/Object.t => FAIL: Tests fail! 3. Apply this patch 4. Repeat (2) => SUCCESS: Tests pass! 5. Sign off :-D Signed-off-by: David Nind Signed-off-by: Marcel de Rooy Signed-off-by: Martin Renvoize --- Koha/Object.pm | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/Koha/Object.pm b/Koha/Object.pm index 5f28c35808..fd24e9947a 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -428,21 +428,29 @@ sub to_api { if ($embeds) { foreach my $embed ( keys %{$embeds} ) { - my $curr = $embed; - my $next = $embeds->{$curr}->{children}; + if ( $embed =~ m/^(?.*)_count$/ + and $embeds->{$embed}->{is_count} ) { - my $children = $self->$curr; - - if ( defined $children and ref($children) eq 'ARRAY' ) { - my @list = map { - $self->_handle_to_api_child( - { child => $_, next => $next, curr => $curr } ) - } @{$children}; - $json_object->{$curr} = \@list; + my $relation = $+{relation}; + $json_object->{$embed} = $self->$relation->count; } else { - $json_object->{$curr} = $self->_handle_to_api_child( - { child => $children, next => $next, curr => $curr } ); + my $curr = $embed; + my $next = $embeds->{$curr}->{children}; + + my $children = $self->$curr; + + if ( defined $children and ref($children) eq 'ARRAY' ) { + my @list = map { + $self->_handle_to_api_child( + { child => $_, next => $next, curr => $curr } ) + } @{$children}; + $json_object->{$curr} = \@list; + } + else { + $json_object->{$curr} = $self->_handle_to_api_child( + { child => $children, next => $next, curr => $curr } ); + } } } } -- 2.39.5