Files
AudioCore/core/services/Database.php

51 lines
1.2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Core\Services;
use PDO;
use PDOException;
class Database
{
private static ?PDO $pdo = null;
public static function get(): ?PDO
{
if (self::$pdo instanceof PDO) {
return self::$pdo;
}
$configPath = __DIR__ . '/../../storage/db.php';
if (!is_file($configPath)) {
return null;
}
$config = require $configPath;
if (!is_array($config)) {
return null;
}
$host = (string)($config['host'] ?? 'localhost');
$db = (string)($config['database'] ?? '');
$user = (string)($config['user'] ?? '');
$pass = (string)($config['pass'] ?? '');
$port = (int)($config['port'] ?? 3306);
if ($db == '' || $user == '') {
return null;
}
$dsn = "mysql:host={$host};dbname={$db};port={$port};charset=utf8mb4";
try {
self::$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
} catch (PDOException $e) {
return null;
}
return self::$pdo;
}
}