From 727750af9390ee95234ce306af5dd3ad944295e4 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 12 Oct 2023 00:03:10 +0100 Subject: [PATCH] Datetime from timestamp (#361) * wip: datetime from timestamp for #360 * wip: suppress excessive class complexity * test: test getting datetime from timestamp --- src/Fetchable.php | 4 ++++ src/Query/SqlQuery.php | 3 ++- test/phpunit/Result/ResultSetTest.php | 13 ++++++++++--- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/Fetchable.php b/src/Fetchable.php index aee8cf1..5ea58ab 100644 --- a/src/Fetchable.php +++ b/src/Fetchable.php @@ -144,6 +144,10 @@ protected function castRow( $key = key($assocArray); $value = $assocArray[$key]; + if($type === Type::DATETIME && is_numeric($value)) { + $value = "@$value"; + } + return match ($type) { Type::BOOL, "boolean" => (bool)$value, Type::INT, "integer" => (int)$value, diff --git a/src/Query/SqlQuery.php b/src/Query/SqlQuery.php index 6bcf6c8..0435a3e 100644 --- a/src/Query/SqlQuery.php +++ b/src/Query/SqlQuery.php @@ -7,6 +7,7 @@ use PDOStatement; use Gt\Database\Result\ResultSet; +/** @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ class SqlQuery extends Query { const SPECIAL_BINDINGS = [ "limit", @@ -204,7 +205,7 @@ private function injectDynamicOr(string $sql, array &$data):string { } $replacementString = ""; - foreach($data["__dynamicOr"] as $i => $kvp) { + foreach($data["__dynamicOr"] as $kvp) { $conditionString = ""; foreach($kvp as $key => $value) { if(is_string($value)) { diff --git a/test/phpunit/Result/ResultSetTest.php b/test/phpunit/Result/ResultSetTest.php index 72572d4..d060954 100644 --- a/test/phpunit/Result/ResultSetTest.php +++ b/test/phpunit/Result/ResultSetTest.php @@ -8,9 +8,9 @@ class ResultSetTest extends TestCase { const FAKE_DATA = [ - ["id" => 1, "name" => "Alice"], - ["id" => 2, "name" => "Bob"], - ["id" => 3, "name" => "Charlie"], + ["id" => 1, "name" => "Alice", "timestamp" => 576264240, "date" => "1988-04-05 17:24"], + ["id" => 2, "name" => "Bob", "timestamp" => 554900700, "date" => "1987-08-02 11:05"], + ["id" => 3, "name" => "Charlie", "timestamp" => 1433548800, "date" => "2015-06-06"], ]; private $fake_data_index = 0; @@ -130,6 +130,13 @@ public function testAsArray() { } } + public function testAsDateTime() { + $resultSet = new ResultSet($this->getStatementMock()); + $row = $resultSet->fetch(); + self::assertEquals("1988-04-05 17:24", $row->getDateTime("date")->format("Y-m-d H:i")); + self::assertEquals("1988-04-05 17:24", $row->getDateTime("timestamp")->format("Y-m-d H:i")); + } + private function getStatementMock():PDOStatement { $statement = $this->createMock(PDOStatement::class); $statement->method("fetch")