From 1d3b224ef6b57dd7040caca3f502bc2495b7257c Mon Sep 17 00:00:00 2001 From: Austin Collier Date: Sat, 16 Mar 2024 18:08:09 -0600 Subject: [PATCH] changed it so PdoWrapper returns collections --- flight/database/PdoWrapper.php | 27 ++++++++++++++++++--------- tests/PdoWrapperTest.php | 7 +++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/flight/database/PdoWrapper.php b/flight/database/PdoWrapper.php index 842038c..4821cb9 100644 --- a/flight/database/PdoWrapper.php +++ b/flight/database/PdoWrapper.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace flight\database; +use flight\util\Collection; use PDO; use PDOStatement; @@ -47,8 +48,9 @@ class PdoWrapper extends PDO */ public function fetchField(string $sql, array $params = []) { - $data = $this->fetchRow($sql, $params); - return reset($data); + $collection_data = $this->fetchRow($sql, $params); + $array_data = $collection_data->getData(); + return reset($array_data); } /** @@ -59,13 +61,13 @@ class PdoWrapper extends PDO * @param string $sql - Ex: "SELECT * FROM table WHERE something = ?" * @param array $params - Ex: [ $something ] * - * @return array + * @return Collection */ - public function fetchRow(string $sql, array $params = []): array + public function fetchRow(string $sql, array $params = []): Collection { $sql .= stripos($sql, 'LIMIT') === false ? ' LIMIT 1' : ''; $result = $this->fetchAll($sql, $params); - return count($result) > 0 ? $result[0] : []; + return count($result) > 0 ? $result[0] : new Collection(); } /** @@ -79,17 +81,24 @@ class PdoWrapper extends PDO * @param string $sql - Ex: "SELECT * FROM table WHERE something = ?" * @param array $params - Ex: [ $something ] * - * @return array> + * @return array */ - public function fetchAll(string $sql, array $params = []): array + public function fetchAll(string $sql, array $params = []) { $processed_sql_data = $this->processInStatementSql($sql, $params); $sql = $processed_sql_data['sql']; $params = $processed_sql_data['params']; $statement = $this->prepare($sql); $statement->execute($params); - $result = $statement->fetchAll(); - return is_array($result) ? $result : []; + $results = $statement->fetchAll(); + if (is_array($results) === true && count($results) > 0) { + foreach ($results as &$result) { + $result = new Collection($result); + } + } else { + $results = []; + } + return $results; } /** diff --git a/tests/PdoWrapperTest.php b/tests/PdoWrapperTest.php index 324c47b..0f41a92 100644 --- a/tests/PdoWrapperTest.php +++ b/tests/PdoWrapperTest.php @@ -88,6 +88,13 @@ class PdoWrapperTest extends TestCase $this->assertEquals('three', $rows[2]['name']); } + public function testFetchAllNoRows() + { + $rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test WHERE 1 = 2'); + $this->assertCount(0, $rows); + $this->assertSame([], $rows); + } + public function testFetchAllWithNamedParams() { $rows = $this->pdo_wrapper->fetchAll('SELECT * FROM test WHERE name = :name', [ 'name' => 'two']);