From d417e053a09782ec334e795d9f59733411452597 Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Tue, 24 Mar 2020 09:33:30 -0300 Subject: [PATCH] Bug 24965: Make Koha::Object->to_api handle undef counts In some cases where we write a class method that is not directly tied to a DBIC relationship (maybe it should) we are following the following pattern: my $related_object = Koha::RelatedObjects->find($params,$attributes); return unless $related_object; return $related_object->some_iterator_on_other_class; While this is not highly consistent (design-wise, because it would be great if we could return an empty iterator instead of undef) we use this broadly and consistently. The to_api method +count handling is not failsafe to those undef cases. And we should make it return 0 instead of trying to get ->count on undefined objects. This patch makes to_api fallback to 0 when it is requested to embed a count. To test: 1. Apply the regression test patch 2. Run: $ kshell k$ prove t/db_dependent/Koha/Object.t => FAIL: Test fails with an error about ->count on undefined variable. 3. Apply this patch 4. Repeat 2 => SUCCESS: The patch adds the simple fallback to 0 on counts 5. Sign off :-D Signed-off-by: Tomas Cohen Arazi Signed-off-by: David Nind --- Koha/Object.pm | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Koha/Object.pm b/Koha/Object.pm index fde0fa9917..180f1ee41f 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -506,7 +506,8 @@ sub to_api { and $embeds->{$embed}->{is_count} ) { my $relation = $+{relation}; - $json_object->{$embed} = $self->$relation->count; + $json_object->{$embed} = + ( defined $self->$relation ) ? $self->$relation->count : 0; } else { my $curr = $embed; -- 2.11.0