diff --git a/Koha/Object.pm b/Koha/Object.pm index 709d7f2f41..22e11b6870 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -21,6 +21,7 @@ package Koha::Object; use Modern::Perl; use Carp; +use Mojo::JSON; use Koha::Database; use Koha::Exceptions::Object; @@ -190,6 +191,61 @@ sub unblessed { return { $self->_result->get_columns }; } +=head3 $object->TO_JSON + +Returns an unblessed representation of the object, suitable for JSON output. + +=cut + +sub TO_JSON { + + my ($self) = @_; + + my $unblessed = $self->unblessed; + my $columns_info = Koha::Database->new->schema->resultset( $self->_type ) + ->result_source->{_columns}; + + foreach my $col ( keys %{$columns_info} ) { + + if ( $columns_info->{$col}->{is_boolean} ) + { # Handle booleans gracefully + $unblessed->{$col} + = ( $unblessed->{$col} ) + ? Mojo::JSON->true + : Mojo::JSON->false; + } + elsif ( _numeric_column_type( $columns_info->{$col}->{data_type} ) ) { + + # TODO: Remove once the solution for + # https://rt.cpan.org/Ticket/Display.html?id=119904 + # is ported to whatever distro we support by that time + $unblessed->{$col} += 0; + } + } + return $unblessed; +} + +sub _numeric_column_type { + # TODO: Remove once the solution for + # https://rt.cpan.org/Ticket/Display.html?id=119904 + # is ported to whatever distro we support by that time + my ($column_type) = @_; + + my @numeric_types = ( + 'bigint', + 'integer', + 'int', + 'mediumint', + 'smallint', + 'tinyint', + 'decimal', + 'double precision', + 'float' + ); + + return ( grep { $column_type eq $_ } @numeric_types) ? 1 : 0; +} + =head3 $object->_result(); Returns the internal DBIC Row object diff --git a/Koha/Objects.pm b/Koha/Objects.pm index 92312066f8..86a5789466 100644 --- a/Koha/Objects.pm +++ b/Koha/Objects.pm @@ -252,6 +252,18 @@ sub unblessed { return [ map { $_->unblessed } $self->as_list ]; } +=head3 Koha::Objects->TO_JSON + +Returns an unblessed representation of objects, suitable for JSON output. + +=cut + +sub TO_JSON { + my ($self) = @_; + + return [ map { $_->TO_JSON } $self->as_list ]; +} + =head3 Koha::Objects->_wrap wraps the DBIC object in a corresponding Koha object