Files
kaffeekasse-saas/app/Core/Database.php
T
2026-06-17 16:45:14 +02:00

52 lines
1.3 KiB
PHP

<?php
namespace App\Core;
use PDO;
use PDOException;
final class Database implements DatabaseInterface
{
private ?PDO $pdo = null;
public function __construct(private readonly array $config)
{
}
public function pdo(): PDO
{
if ($this->pdo instanceof PDO) {
return $this->pdo;
}
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
$this->config['host'],
$this->config['port'],
$this->config['name'],
$this->config['charset']
);
try {
$this->pdo = new PDO($dsn, $this->config['user'], $this->config['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $exception) {
throw new PDOException(
'Database connection failed: ' . $exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
return $this->pdo;
}
public function isConfigured(): bool
{
return $this->config['name'] !== '' && $this->config['user'] !== '';
}
}