diff options
Diffstat (limited to 'src/DB.php')
-rw-r--r-- | src/DB.php | 78 |
1 files changed, 78 insertions, 0 deletions
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 @@ +<?php + +namespace App; + +class DB { + private static \PDO $connection; + + public static function init(): void + { + $driver = $_ENV['DB_DRIVER'] ?? 'pgsql'; + $host = $_ENV['DB_HOST'] ?? 'db'; + $dbname = $_ENV['DB_NAME']; + $user = $_ENV['DB_USER']; + $password = $_ENV['DB_PASSWORD']; + + self::$connection = new \PDO("pgsql:host=$host;dbname=$dbname", $user, $password); + } + + /** + * @param string $query + * @param array $params + */ + public static function query(string $query, array $params = []): \PDOStatement|false + { + /**@var \PDOStatement $statement*/ + $statement = self::$connection->prepare($query); + $statement->execute($params); + + return $statement; + } + + /** + * @param string $class + * @param string $query + * @param array $params + * + * @return array<object> + */ + 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; + } +} |