game/_incl_data/class/Core/Db.php

157 lines
3.3 KiB
PHP

<?php
namespace Core;
use PDO;
use PDOException;
use PDOStatement;
class Db
{
private static PDO $db;
private static self $instance;
/**
* DB constructor.
* @throws PDOException
*/
public function __construct()
{
try {
self::$db = Database::pdoinit();
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
/**
* @param string $query
* @return false|int
*/
public static function exec(string $query): false|int
{
self::init();
return self::$db->exec($query);
}
private static function init(): void
{
self::$instance ??= new self();
}
/**
* @param ?string $name [optional] Name of the sequence object from which the ID should be returned.
* @return false|string
*/
public static function lastInsertId(?string $name = null): false|string
{
self::init();
return self::$db->lastInsertId($name);
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getRows(string $query, array $args = []): array
{
$stmt = self::run($query, $args)->fetchAll();
if (!$stmt) {
return [];
}
return $stmt;
}
/**
* @param string $query
* @param array $args
* @return false|PDOStatement
*/
public static function run(string $query, array $args = []): false|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 $stmt
* @return false|PDOStatement
*/
private static function query(string $stmt): false|PDOStatement
{
self::init();
return self::$db->query($stmt);
}
/**
* @param string $stmt
* @return false|PDOStatement
*/
public static function prepare(string $stmt): false|PDOStatement
{
self::init();
return self::$db->prepare($stmt);
}
/**
* @param string $query
* @param array $args
* @return mixed
*/
public static function getValue(string $query, array $args = []): mixed
{
$result = self::getRow($query, $args);
if (!empty($result)) {
return array_shift($result);
}
return '';
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getRow(string $query, array $args = []): array
{
$stmt = self::run($query, $args)->fetch();
if (!$stmt) {
return [];
}
return $stmt;
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getColumn(string $query, array $args = []): array
{
$stmt = self::run($query, $args)->fetchAll(PDO::FETCH_COLUMN);
if (!$stmt) {
return [];
}
return $stmt;
}
/**
* @param string $query
* @param array $args
*/
public static function sql(string $query, array $args = []): void
{
self::run($query, $args);
}
}