Browse Source

Bug 18539: Forbid list context calls for Koha::Objects->find

Reading https://perlmaven.com/how-to-return-undef-from-a-function
this sound like the more correct behaviour.

Considering:
$template->param(
    stuff => Koha::Stuffs->find( $id ),
    foo   => 1,
);
without this patch, if the $id does not represent any rows in the DB,
stuff will be assigned to 'foo' and $foo will be undef in the template.
That can lead to very bad side-effects.

With this patch we make sure that it will never happen again.

Test plan:
  prove t/db_dependent/Koha/Objects.t
should return green

Signed-off-by: Marc Véron <veron@veron.ch>

Signed-off-by: Nick Clemens <nick@bywatersolutions.com>

Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
17.11.x
Jonathan Druart 7 years ago
parent
commit
15cbf14f4d
  1. 2
      Koha/Objects.pm
  2. 12
      t/db_dependent/Koha/Objects.t

2
Koha/Objects.pm

@ -78,6 +78,8 @@ my $object = Koha::Objects->find( { keypart1 => $keypart1, keypart2 => $keypart2
sub find {
my ( $self, $id ) = @_;
croak 'Cannot use "->find" in list context' if wantarray;
return unless defined($id);
my $result = $self->_resultset()->find($id);

12
t/db_dependent/Koha/Objects.t

@ -19,7 +19,7 @@
use Modern::Perl;
use Test::More tests => 13;
use Test::More tests => 14;
use Test::Warn;
use Koha::Authority::Types;
@ -43,6 +43,16 @@ my @columns = Koha::Patrons->columns;
my $borrowernumber_exists = grep { /^borrowernumber$/ } @columns;
is( $borrowernumber_exists, 1, 'Koha::Objects->columns should return the table columns' );
subtest 'find' => sub {
plan tests => 2;
my $patron = $builder->build({source => 'Borrower'});
my $patron_object = Koha::Patrons->find( $patron->{borrowernumber} );
is( $patron_object->borrowernumber, $patron->{borrowernumber}, '->find should return the correct object' );
eval { my @patrons = Koha::Patrons->find( $patron->{borrowernumber} ); };
like( $@, qr|^Cannot use "->find" in list context|, "->find should not be called in list context to avoid side-effects" );
};
subtest 'update' => sub {
plan tests => 2;

Loading…
Cancel
Save