From 54de74c6f67c1caa6e1126ceae7e6d67d6f17e03 Mon Sep 17 00:00:00 2001 From: Lari Taskula Date: Fri, 24 Mar 2017 15:29:30 +0200 Subject: [PATCH] Bug 18330: Handle date-time in Koha::Object->TO_JSON This patch formats timestamps and datetimes to meet date-time definition in RFC3339, as required by Swagger documentation. Signed-off-by: Benjamin Rokseth Signed-off-by: Tomas Cohen Arazi Signed-off-by: Jonathan Druart --- Koha/Object.pm | 21 +++++++++++++++++++++ t/db_dependent/Koha/Object.t | 26 ++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Koha/Object.pm b/Koha/Object.pm index d305542200..fc30adc2b3 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -25,6 +25,7 @@ use Mojo::JSON; use Koha::Database; use Koha::Exceptions::Object; +use Koha::DateUtils; =head1 NAME @@ -221,10 +222,30 @@ sub TO_JSON { # is ported to whatever distro we support by that time $unblessed->{$col} += 0; } + elsif ( _datetime_column_type( $columns_info->{$col}->{data_type} ) ) { + eval { + return undef unless $unblessed->{$col}; + $unblessed->{$col} = output_pref({ + dateformat => 'rfc3339', + dt => dt_from_string($unblessed->{$col}, 'sql'), + }); + }; + } } return $unblessed; } +sub _datetime_column_type { + my ($column_type) = @_; + + my @dt_types = ( + 'timestamp', + 'datetime' + ); + + return ( grep { $column_type eq $_ } @dt_types) ? 1 : 0; +} + sub _numeric_column_type { # TODO: Remove once the solution for # https://rt.cpan.org/Ticket/Display.html?id=119904 diff --git a/t/db_dependent/Koha/Object.t b/t/db_dependent/Koha/Object.t index a506b89ccc..5f91415596 100755 --- a/t/db_dependent/Koha/Object.t +++ b/t/db_dependent/Koha/Object.t @@ -146,18 +146,23 @@ subtest 'discard_changes' => sub { subtest 'TO_JSON tests' => sub { - plan tests => 5; + plan tests => 7; $schema->storage->txn_begin; + my $dt = dt_from_string(); my $borrowernumber = $builder->build( { source => 'Borrower', value => { lost => 1, - gonenoaddress => 0 } })->{borrowernumber}; + gonenoaddress => 0, + updated_on => $dt, + lastseen => $dt, } })->{borrowernumber}; my $patron = Koha::Patrons->find($borrowernumber); my $lost = $patron->TO_JSON()->{lost}; my $gonenoaddress = $patron->TO_JSON->{gonenoaddress}; + my $updated_on = $patron->TO_JSON->{updated_on}; + my $lastseen = $patron->TO_JSON->{lastseen}; ok( $lost->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' ); is( $lost, 1, 'Boolean attribute value is correct (true)' ); @@ -167,6 +172,23 @@ subtest 'TO_JSON tests' => sub { ok( !isvstring($patron->borrowernumber), 'Integer values are not coded as strings' ); + my $rfc3999_regex = qr/ + (?\d{4}) + - + (?\d{2}) + - + (?\d{2}) + ([Tt\s]) + (?\d{2}) + : + (?\d{2}) + : + (?\d{2}) + (([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9])) + /xms; + like( $updated_on, $rfc3999_regex, "Date-time $updated_on formatted correctly"); + like( $lastseen, $rfc3999_regex, "Date-time $updated_on formatted correctly"); + $schema->storage->txn_rollback; }; -- 2.39.5