From f591f0a613eaaf07978b50b113cc1ddf748c71f5 Mon Sep 17 00:00:00 2001
From: Marcel de Rooy <m.de.rooy@rijksmuseum.nl>
Date: Thu, 27 Oct 2016 09:11:03 +0200
Subject: [PATCH] Bug 17502: Add type check to output_pref

This patch makes the following changes:
[1] In Koha/DateUtils.pm, sub output_pref:
    Add a test if $dt is really a DateTime before calling method ymd.
    Preventing a crash like:
    Can't locate object method "ymd" via package "dateonly".
    See also BZ 17502/15822.
[2] Adds a few unit tests in t/DateUtils.t.

Test plan:
[1] Run the adjusted unit test t/DateUtils.t

Signed-off-by: Marcel de Rooy <m.de.rooy@rijksmuseum.nl>
Signed-off-by: Josef Moravec <josef.moravec@gmail.com>

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
---
 Koha/DateUtils.pm | 2 +-
 t/DateUtils.t     | 9 ++++++++-
 2 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/Koha/DateUtils.pm b/Koha/DateUtils.pm
index 51d3d93..1bc4ec7 100644
--- a/Koha/DateUtils.pm
+++ b/Koha/DateUtils.pm
@@ -219,7 +219,7 @@ sub output_pref {
         carp "Invalid date '$str' passed to output_pref\n" if $@;
     }
 
-    return unless defined $dt;
+    return unless defined $dt && ref($dt) eq 'DateTime';
 
     # FIXME: see bug 13242 => no TZ for dates 'infinite'
     if ( $dt->ymd !~ /^9999/ ) {
diff --git a/t/DateUtils.t b/t/DateUtils.t
index 47cf1c5..6550167 100755
--- a/t/DateUtils.t
+++ b/t/DateUtils.t
@@ -4,7 +4,7 @@ use DateTime::TimeZone;
 
 use C4::Context;
 
-use Test::More tests => 60;
+use Test::More tests => 63;
 
 use Test::MockModule;
 use Test::Warn;
@@ -222,6 +222,13 @@ is( output_pref( { dt => $dt, dateonly => 1 } ), '01/01/1900', 'dt_from_string s
 $dt = dt_from_string('2015-01-31 01:02:03');
 is( output_pref( {dt => $dt} ), '31/01/2015 01:02', 'dt_from_string should fallback to sql format' );
 
+# output_pref with no parameters, single parameter (no hash)
+is( output_pref(), undef, 'output_pref without parameters' );
+is( output_pref( 'no_dt' ), undef, 'Passed single invalid dt to output_pref' );
+
+# pass invalid dt via hash
+is( output_pref({ dt => 'no_dt' }), undef, 'Passed invalid dt in hash to output_pref' );
+
 # output_pref with str parameter
 is( output_pref( { 'str' => $testdate_iso, dateformat => 'iso', dateonly => 1 } ), $testdate_iso, 'output_pref should handle correctly the iso parameter' );
 my $output_for_invalid_date;
-- 
2.9.3