Browse Source

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 <david@davidnind.com>
Signed-off-by: Marcel de Rooy <m.de.rooy@rijksmuseum.nl>
Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
20.05.x
Tomás Cohen Arazi 4 years ago
committed by Martin Renvoize
parent
commit
58356c12bb
Signed by: martin.renvoize GPG Key ID: 422B469130441A0F
  1. 32
      Koha/Object.pm

32
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/^(?<relation>.*)_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 } );
}
}
}
}

Loading…
Cancel
Save