From 03b4ed2f00ce9129bdae43b36a4e0ea482299332 Mon Sep 17 00:00:00 2001 From: Kyle M Hall Date: Tue, 2 Apr 2019 07:19:17 -0400 Subject: [PATCH] Bug 22622: Add Koha::Object method _new_from_hashref It may be useful to be able to instantiate a Koha::Object from data already fetched from the database. This might be used for compatibility with legacy code, or perhaps for use with optimized queries. --- Koha/Object.pm | 14 ++++++++++++++ t/db_dependent/Koha/Object.t | 21 ++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Koha/Object.pm b/Koha/Object.pm index 11074498ba..4628a6d4e2 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -107,6 +107,20 @@ sub _new_from_dbic { } +=head3 Koha::Object->_new_from_hashref(); + +my $object = Koha::Object->_new_from_hashref($hashref_row); + +=cut + +sub _new_from_hashref { + my ( $class, $hashref ) = @_; + + my $result = Koha::Database->new->schema->resultset( $class->_type )->new( $hashref ); + + $class->_new_from_dbic( $result ); +} + =head3 $object->store(); Saves the object in storage. diff --git a/t/db_dependent/Koha/Object.t b/t/db_dependent/Koha/Object.t index 40f117007e..72b8eb0643 100755 --- a/t/db_dependent/Koha/Object.t +++ b/t/db_dependent/Koha/Object.t @@ -17,7 +17,7 @@ use Modern::Perl; -use Test::More tests => 19; +use Test::More tests => 20; use Test::Exception; use Test::Warn; use DateTime; @@ -818,3 +818,22 @@ subtest 'prefetch_whitelist() tests' => sub { $schema->storage->txn_rollback; }; + +subtest 'new_from_hashref' => sub { + plan tests => 1; + + $schema->storage->txn_begin; + + my $categorycode = $builder->build({ source => 'Category' })->{categorycode}; + my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + + my $patron1 = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store; + + my $hashref = $patron1->unblessed; + + my $patron2 = Koha::Patron->_new_from_hashref( $hashref ); + + is( $patron1->id, $patron2->id, "Borrowernumbers match using new_from_hashref"); + + $schema->storage->txn_rollback; +}; -- 2.21.1 (Apple Git-122.3)