game/_incl_data/class/Core/Db.php
2022-12-30 21:03:50 +02:00

144 lines
2.9 KiB
PHP

<?php
namespace Core;
use Exception;
use PDO;
use PDOException;
use PDOStatement;
class Db
{
private static PDO $db;
private static self $instance;
/**
* DB constructor.
* @throws Exception
*/
public function __construct()
{
try {
self::$db = Database::pdoinit();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
private static function init(): void
{
self::$instance ??= new self();
}
/**
* @param string $stmt
* @return PDOStatement
*/
private static function query(string $stmt): PDOStatement
{
self::init();
return self::$db->query($stmt);
}
/**
* @param string $stmt
* @return PDOStatement
*/
public static function prepare(string $stmt): PDOStatement
{
self::init();
return self::$db->prepare($stmt);
}
/**
* @param string $query
* @return int
*/
static public function exec(string $query): int
{
self::init();
return self::$db->exec($query);
}
/**
* @return string
*/
static public function lastInsertId(): string
{
self::init();
return self::$db->lastInsertId();
}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public static function run(string $query, array $args = []): PDOStatement
{
try {
if (!$args) {
return self::query($query);
}
$stmt = self::prepare($query);
$stmt->execute($args);
return $stmt;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
/**
* @param string $query
* @param array $args
* @return mixed
*/
public static function getRow(string $query, array $args = [])
{
return self::run($query, $args)->fetch();
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getRows(string $query, array $args = []): array
{
return self::run($query, $args)->fetchAll();
}
/**
* @param string $query
* @param array $args
* @return mixed
*/
public static function getValue(string $query, array $args = [])
{
$result = self::getRow($query, $args);
if (!empty($result)) {
$result = array_shift($result);
}
return $result;
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getColumn(string $query, array $args = []): array
{
return self::run($query, $args)->fetchAll(PDO::FETCH_COLUMN);
}
/**
* @param string $query
* @param array $args
*/
public static function sql(string $query, array $args = [])
{
self::run($query, $args);
}
}