From fa00b957378a393f8edbfc98ef111d35d18ecb09 Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Sun, 24 Sep 2023 13:40:25 +0200 Subject: initial commit --- src/DB.php | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/DB.php (limited to 'src/DB.php') diff --git a/src/DB.php b/src/DB.php new file mode 100644 index 0000000..4e34d32 --- /dev/null +++ b/src/DB.php @@ -0,0 +1,78 @@ +prepare($query); + $statement->execute($params); + + return $statement; + } + + /** + * @param string $class + * @param string $query + * @param array $params + * + * @return array + */ + public static function fetch(string $class, string $query, array $params = []): array + { + $rows = DB::query($query, $params)->fetchAll(\PDO::FETCH_ASSOC); + + $results = []; + foreach ($rows as $row) { + $results[] = DB::convertToModel($class, $row); + } + + return $results; + } + + /** + * @param string $class + * @param array $row + * + * @return object + */ + public static function convertToModel(string $class, array $row): object + { + $object = new $class(); + + foreach ($row as $columnKey => $columnValue) { + $objectKey = explode('_', $columnKey); + $objectKey = $objectKey[0] . implode('', array_map('ucwords', array_slice($objectKey, 1))); + + if (property_exists($object, $objectKey)) { + $propertyType = (new \ReflectionProperty($object, $objectKey))->getType(); + + if (class_exists($propertyType->getName())) { + $object->$objectKey = new ($propertyType->getName())($columnValue); + } else { + $object->$objectKey = $columnValue; + } + } + } + + return $object; + } +} -- cgit v1.2.3