From ba476ee93cc5784e5cce49456050c5af736b994d Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Mon, 11 Nov 2019 16:07:03 -0300 Subject: [PATCH] Bug 23893: Add new_from_api and set_from_api to Koha::Object This patch introduces the following methods to the Koha::Object class: - set_from_api - new_from_api This methods are going to be used when writing API controllers that map to the attributes to the DB schema ones. To test: 1. Apply this patchset 2. Run: $ kshell k$ prove t/db_dependent/Koha/Object.t => SUCCESS: Tests pass! 3. Sign off :-D --- Koha/Object.pm | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Koha/Object.pm b/Koha/Object.pm index 92ac58ccac..69cdf0fa07 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -430,6 +430,50 @@ sub from_api_mapping { return $self->{_from_api_mapping}; } +=head3 new_from_api + + my $object = Koha::Object->new_from_api; + my $object = Koha::Object->new_from_api( $attrs ); + +Creates a new object, mapping the API attribute names to the ones on the DB schema. + +=cut + +sub new_from_api { + my ( $class, $params ) = @_; + + my $self = $class->new; + return $self->set_from_api( $params ); +} + +=head3 set_from_api + + my $object = Koha::Object->new(...); + $object->set_from_api( $attrs ) + +Sets the object's attributes mapping API attribute names to the ones on the DB schema. + +=cut + +sub set_from_api { + my ( $self, $from_api_params ) = @_; + + my $from_api_mapping = $self->from_api_mapping; + + my $params; + + while (my ($key, $value) = each %{ $from_api_params } ) { + if ( exists $from_api_mapping->{$key} ) { + $params->{$from_api_mapping->{$key}} = $value; + } + else { + $params->{$key} = $value; + } + } + + return $self->set( $params ); +} + =head3 $object->unblessed_all_relateds my $everything_into_one_hashref = $object->unblessed_all_relateds -- 2.24.0