From 4630e1818fc48822050110a900a04a92ee573a4e Mon Sep 17 00:00:00 2001 From: David Grudl Date: Tue, 13 Oct 2015 14:39:24 +0200 Subject: [PATCH] Result: normalizes invalid date to NULL --- src/Dibi/Result.php | 2 ++ tests/dibi/Result.normalize.phpt | 37 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/Dibi/Result.php b/src/Dibi/Result.php index a7547ad8..fc7f88b9 100644 --- a/src/Dibi/Result.php +++ b/src/Dibi/Result.php @@ -518,6 +518,8 @@ class Result implements IDataSource if ((int) $value !== 0 || substr((string) $value, 0, 3) === '00:') { // '', NULL, FALSE, '0000-00-00', ... $value = new DateTime($value); $row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]); + } else { + $row[$key] = NULL; } } elseif ($type === Type::BINARY) { diff --git a/tests/dibi/Result.normalize.phpt b/tests/dibi/Result.normalize.phpt index 6ceaf918..26898709 100644 --- a/tests/dibi/Result.normalize.phpt +++ b/tests/dibi/Result.normalize.phpt @@ -155,3 +155,40 @@ test(function () { Assert::same(['col' => 1], $result->test(['col' => 1])); Assert::same(['col' => 1], $result->test(['col' => 1.0])); }); + + +test(function () { + $result = new MockResult; + $result->setType('col', Type::DATETIME); + + Assert::same(['col' => NULL], $result->test(['col' => NULL])); + Assert::exception(function () use ($result) { + $result->test(['col' => TRUE]); + }, 'Exception'); + Assert::same(['col' => NULL], $result->test(['col' => FALSE])); + + Assert::same(['col' => NULL], $result->test(['col' => ''])); + Assert::same(['col' => NULL], $result->test(['col' => '0000-00-00'])); + Assert::equal(['col' => new Dibi\DateTime('00:00:00')], $result->test(['col' => '00:00:00'])); + Assert::equal(['col' => new Dibi\DateTime('2015-10-13')], $result->test(['col' => '2015-10-13'])); + Assert::equal(['col' => new Dibi\DateTime('2015-10-13 14:30')], $result->test(['col' => '2015-10-13 14:30'])); +}); + + +test(function () { + $result = new MockResult; + $result->setType('col', Type::DATETIME); + $result->setFormat(Type::DATETIME, 'Y-m-d H:i:s'); + + Assert::same(['col' => NULL], $result->test(['col' => NULL])); + Assert::exception(function () use ($result) { + $result->test(['col' => TRUE]); + }, 'Exception'); + Assert::same(['col' => NULL], $result->test(['col' => FALSE])); + + Assert::same(['col' => NULL], $result->test(['col' => ''])); + Assert::same(['col' => NULL], $result->test(['col' => '0000-00-00'])); + Assert::same(['col' => date('Y-m-d 00:00:00')], $result->test(['col' => '00:00:00'])); + Assert::equal(['col' => '2015-10-13 00:00:00'], $result->test(['col' => '2015-10-13'])); + Assert::equal(['col' => '2015-10-13 14:30:00'], $result->test(['col' => '2015-10-13 14:30'])); +});