Bug 19979: Fix get_facets_info test in Search.t
[koha.git] / Koha / Object.pm
blob7f36a7dc1554344ed18f56fc70dabf616ba4568f
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->_result();
298 Returns the internal DBIC Row object
300 =cut
302 sub _result {
303 my ($self) = @_;
305 # If we don't have a dbic row at this point, we need to create an empty one
306 $self->{_result} ||=
307 Koha::Database->new()->schema()->resultset( $self->_type() )->new({});
309 return $self->{_result};
312 =head3 $object->_columns();
314 Returns an arrayref of the table columns
316 =cut
318 sub _columns {
319 my ($self) = @_;
321 # If we don't have a dbic row at this point, we need to create an empty one
322 $self->{_columns} ||= [ $self->_result()->result_source()->columns() ];
324 return $self->{_columns};
327 =head3 AUTOLOAD
329 The autoload method is used only to get and set values for an objects properties.
331 =cut
333 sub AUTOLOAD {
334 my $self = shift;
336 my $method = our $AUTOLOAD;
337 $method =~ s/.*://;
339 my @columns = @{$self->_columns()};
340 # Using direct setter/getter like $item->barcode() or $item->barcode($barcode);
341 if ( grep {/^$method$/} @columns ) {
342 if ( @_ ) {
343 $self->_result()->set_column( $method, @_ );
344 return $self;
345 } else {
346 my $value = $self->_result()->get_column( $method );
347 return $value;
351 my @known_methods = qw( is_changed id in_storage get_column discard_changes update );
352 Koha::Exceptions::Object::MethodNotCoveredByTests->throw( "The method $method is not covered by tests!" ) unless grep {/^$method$/} @known_methods;
354 my $r = eval { $self->_result->$method(@_) };
355 if ( $@ ) {
356 Koha::Exceptions::Object->throw( ref($self) . "::$method generated this error: " . $@ );
358 return $r;
361 =head3 _type
363 This method must be defined in the child class. The value is the name of the DBIC resultset.
364 For example, for borrowers, the _type method will return "Borrower".
366 =cut
368 sub _type { }
370 sub DESTROY { }
372 =head1 AUTHOR
374 Kyle M Hall <kyle@bywatersolutions.com>
376 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
378 =cut