Bug 14769: (Follow-up) Reduce number of preference parses
[koha.git] / Koha / Object.pm
blob00e0c243a8748c31f2643889be87471c1c1b7312
1 package Koha::Object;
3 # Copyright ByWater Solutions 2014
4 # Copyright 2016 Koha Development Team
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 3 of the License, or (at your option) any later
11 # version.
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 use Modern::Perl;
23 use Carp;
24 use Mojo::JSON;
25 use Try::Tiny;
27 use Koha::Database;
28 use Koha::Exceptions::Object;
29 use Koha::DateUtils;
31 =head1 NAME
33 Koha::Object - Koha Object base class
35 =head1 SYNOPSIS
37 use Koha::Object;
38 my $object = Koha::Object->new({ property1 => $property1, property2 => $property2, etc... } );
40 =head1 DESCRIPTION
42 This class must always be subclassed.
44 =head1 API
46 =head2 Class Methods
48 =cut
50 =head3 Koha::Object->new();
52 my $object = Koha::Object->new();
53 my $object = Koha::Object->new($attributes);
55 Note that this cannot be used to retrieve record from the DB.
57 =cut
59 sub new {
60 my ( $class, $attributes ) = @_;
61 my $self = {};
63 if ($attributes) {
64 my $schema = Koha::Database->new->schema;
66 # Remove the arguments which exist, are not defined but NOT NULL to use the default value
67 my $columns_info = $schema->resultset( $class->_type )->result_source->columns_info;
68 for my $column_name ( keys %$attributes ) {
69 my $c_info = $columns_info->{$column_name};
70 next if $c_info->{is_nullable};
71 next if not exists $attributes->{$column_name} or defined $attributes->{$column_name};
72 delete $attributes->{$column_name};
74 $self->{_result} = $schema->resultset( $class->_type() )
75 ->new($attributes);
78 croak("No _type found! Koha::Object must be subclassed!")
79 unless $class->_type();
81 bless( $self, $class );
85 =head3 Koha::Object->_new_from_dbic();
87 my $object = Koha::Object->_new_from_dbic($dbic_row);
89 =cut
91 sub _new_from_dbic {
92 my ( $class, $dbic_row ) = @_;
93 my $self = {};
95 # DBIC result row
96 $self->{_result} = $dbic_row;
98 croak("No _type found! Koha::Object must be subclassed!")
99 unless $class->_type();
101 croak( "DBIC result _type " . ref( $self->{_result} ) . " isn't of the _type " . $class->_type() )
102 unless ref( $self->{_result} ) eq "Koha::Schema::Result::" . $class->_type();
104 bless( $self, $class );
108 =head3 $object->store();
110 Saves the object in storage.
111 If the object is new, it will be created.
112 If the object previously existed, it will be updated.
114 Returns:
115 $self if the store was a success
116 undef if the store failed
118 =cut
120 sub store {
121 my ($self) = @_;
123 try {
124 return $self->_result()->update_or_insert() ? $self : undef;
126 catch {
127 # Catch problems and raise relevant exceptions
128 if (ref($_) eq 'DBIx::Class::Exception') {
129 if ( $_->{msg} =~ /Cannot add or update a child row: a foreign key constraint fails/ ) {
130 # FK constraints
131 # FIXME: MySQL error, if we support more DB engines we should implement this for each
132 if ( $_->{msg} =~ /FOREIGN KEY \(`(?<column>.*?)`\)/ ) {
133 Koha::Exceptions::Object::FKConstraint->throw(
134 error => 'Broken FK constraint',
135 broken_fk => $+{column}
139 elsif( $_->{msg} =~ /Duplicate entry '(.*?)' for key '(?<key>.*?)'/ ) {
140 Koha::Exceptions::Object::DuplicateID->throw(
141 error => 'Duplicate ID',
142 duplicate_id => $+{key}
146 # Catch-all for foreign key breakages. It will help find other use cases
147 $_->rethrow();
151 =head3 $object->delete();
153 Removes the object from storage.
155 Returns:
156 1 if the deletion was a success
157 0 if the deletion failed
158 -1 if the object was never in storage
160 =cut
162 sub delete {
163 my ($self) = @_;
165 # Deleting something not in storage throws an exception
166 return -1 unless $self->_result()->in_storage();
168 # Return a boolean for succcess
169 return $self->_result()->delete() ? 1 : 0;
172 =head3 $object->set( $properties_hashref )
174 $object->set(
176 property1 => $property1,
177 property2 => $property2,
178 property3 => $propery3,
182 Enables multiple properties to be set at once
184 Returns:
185 1 if all properties were set.
186 0 if one or more properties do not exist.
187 undef if all properties exist but a different error
188 prevents one or more properties from being set.
190 If one or more of the properties do not exist,
191 no properties will be set.
193 =cut
195 sub set {
196 my ( $self, $properties ) = @_;
198 my @columns = @{$self->_columns()};
200 foreach my $p ( keys %$properties ) {
201 unless ( grep {/^$p$/} @columns ) {
202 Koha::Exceptions::Object::PropertyNotFound->throw( "No property $p for " . ref($self) );
206 return $self->_result()->set_columns($properties) ? $self : undef;
209 =head3 $object->unblessed();
211 Returns an unblessed representation of object.
213 =cut
215 sub unblessed {
216 my ($self) = @_;
218 return { $self->_result->get_columns };
221 =head3 $object->TO_JSON
223 Returns an unblessed representation of the object, suitable for JSON output.
225 =cut
227 sub TO_JSON {
229 my ($self) = @_;
231 my $unblessed = $self->unblessed;
232 my $columns_info = Koha::Database->new->schema->resultset( $self->_type )
233 ->result_source->{_columns};
235 foreach my $col ( keys %{$columns_info} ) {
237 if ( $columns_info->{$col}->{is_boolean} )
238 { # Handle booleans gracefully
239 $unblessed->{$col}
240 = ( $unblessed->{$col} )
241 ? Mojo::JSON->true
242 : Mojo::JSON->false;
244 elsif ( _numeric_column_type( $columns_info->{$col}->{data_type} ) ) {
246 # TODO: Remove once the solution for
247 # https://rt.cpan.org/Ticket/Display.html?id=119904
248 # is ported to whatever distro we support by that time
249 $unblessed->{$col} += 0;
251 elsif ( _datetime_column_type( $columns_info->{$col}->{data_type} ) ) {
252 eval {
253 return unless $unblessed->{$col};
254 $unblessed->{$col} = output_pref({
255 dateformat => 'rfc3339',
256 dt => dt_from_string($unblessed->{$col}, 'sql'),
261 return $unblessed;
264 sub _datetime_column_type {
265 my ($column_type) = @_;
267 my @dt_types = (
268 'timestamp',
269 'datetime'
272 return ( grep { $column_type eq $_ } @dt_types) ? 1 : 0;
275 sub _numeric_column_type {
276 # TODO: Remove once the solution for
277 # https://rt.cpan.org/Ticket/Display.html?id=119904
278 # is ported to whatever distro we support by that time
279 my ($column_type) = @_;
281 my @numeric_types = (
282 'bigint',
283 'integer',
284 'int',
285 'mediumint',
286 'smallint',
287 'tinyint',
288 'decimal',
289 'double precision',
290 'float'
293 return ( grep { $column_type eq $_ } @numeric_types) ? 1 : 0;
296 =head3 $object->unblessed_all_relateds
298 my $everything_into_one_hashref = $object->unblessed_all_relateds
300 The unblessed method only retrieves column' values for the column of the object.
301 In a *few* cases we want to retrieve the information of all the prefetched data.
303 =cut
305 sub unblessed_all_relateds {
306 my ($self) = @_;
308 my %data;
309 my $related_resultsets = $self->_result->{related_resultsets} || {};
310 my $rs = $self;
311 while ( $related_resultsets and %$related_resultsets ) {
312 my @relations = keys %{ $related_resultsets };
313 if ( @relations ) {
314 my $relation = $relations[0];
315 $rs = $rs->related_resultset($relation)->get_cache;
316 $rs = $rs->[0]; # Does it makes sense to have several values here?
317 my $object_class = Koha::Object::_get_object_class( $rs->result_class );
318 my $koha_object = $object_class->_new_from_dbic( $rs );
319 $related_resultsets = $rs->{related_resultsets};
320 %data = ( %data, %{ $koha_object->unblessed } );
323 %data = ( %data, %{ $self->unblessed } );
324 return \%data;
327 =head3 $object->_result();
329 Returns the internal DBIC Row object
331 =cut
333 sub _result {
334 my ($self) = @_;
336 # If we don't have a dbic row at this point, we need to create an empty one
337 $self->{_result} ||=
338 Koha::Database->new()->schema()->resultset( $self->_type() )->new({});
340 return $self->{_result};
343 =head3 $object->_columns();
345 Returns an arrayref of the table columns
347 =cut
349 sub _columns {
350 my ($self) = @_;
352 # If we don't have a dbic row at this point, we need to create an empty one
353 $self->{_columns} ||= [ $self->_result()->result_source()->columns() ];
355 return $self->{_columns};
358 sub _get_object_class {
359 my ( $type ) = @_;
360 return unless $type;
362 if( $type->can('koha_object_class') ) {
363 return $type->koha_object_class;
365 $type =~ s|Schema::Result::||;
366 return ${type};
369 =head3 AUTOLOAD
371 The autoload method is used only to get and set values for an objects properties.
373 =cut
375 sub AUTOLOAD {
376 my $self = shift;
378 my $method = our $AUTOLOAD;
379 $method =~ s/.*://;
381 my @columns = @{$self->_columns()};
382 # Using direct setter/getter like $item->barcode() or $item->barcode($barcode);
383 if ( grep {/^$method$/} @columns ) {
384 if ( @_ ) {
385 $self->_result()->set_column( $method, @_ );
386 return $self;
387 } else {
388 my $value = $self->_result()->get_column( $method );
389 return $value;
393 my @known_methods = qw( is_changed id in_storage get_column discard_changes update related_resultset );
395 Koha::Exceptions::Object::MethodNotCoveredByTests->throw( "The method $method is not covered by tests!" ) unless grep {/^$method$/} @known_methods;
397 my $r = eval { $self->_result->$method(@_) };
398 if ( $@ ) {
399 Koha::Exceptions::Object->throw( ref($self) . "::$method generated this error: " . $@ );
401 return $r;
404 =head3 _type
406 This method must be defined in the child class. The value is the name of the DBIC resultset.
407 For example, for borrowers, the _type method will return "Borrower".
409 =cut
411 sub _type { }
413 sub DESTROY { }
415 =head1 AUTHOR
417 Kyle M Hall <kyle@bywatersolutions.com>
419 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
421 =cut