95 lines
2.6 KiB
PHP
95 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Infrastructure;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
use RuntimeException;
|
|
|
|
final class Database
|
|
{
|
|
private static ?PDO $pdo = null;
|
|
|
|
public static function get(): PDO
|
|
{
|
|
if (self::$pdo instanceof PDO) {
|
|
return self::$pdo;
|
|
}
|
|
|
|
$get = static function (string $k, ?string $default = null): ?string {
|
|
$v = getenv($k);
|
|
if ($v !== false && $v !== '') {
|
|
return (string)$v;
|
|
}
|
|
return $_ENV[$k] ?? $default;
|
|
};
|
|
|
|
$dsn = $get('DB_DSN');
|
|
$user = $get('DB_USER');
|
|
$pass = $get('DB_PASS');
|
|
|
|
if (!$dsn) {
|
|
$host = $get('DB_HOST', 'localhost');
|
|
$port = $get('DB_PORT', '5432');
|
|
$name = $get('DB_NAME');
|
|
if ($name) {
|
|
$dsn = sprintf('pgsql:host=%s;port=%s;dbname=%s', $host, $port, $name);
|
|
}
|
|
}
|
|
|
|
if (!$dsn) {
|
|
throw new RuntimeException('DB_DSN manquant (ni DB_DSN ni DB_HOST/DB_PORT/DB_NAME).');
|
|
}
|
|
|
|
try {
|
|
$pdo = new PDO($dsn, (string)($user ?? ''), (string)($pass ?? ''), [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
]);
|
|
return self::$pdo = $pdo;
|
|
} catch (PDOException $e) {
|
|
throw new RuntimeException('Connexion BDD échouée.', previous: $e);
|
|
}
|
|
}
|
|
|
|
/** @deprecated Utiliser Database::get() */
|
|
public static function pdo(): PDO
|
|
{
|
|
@trigger_error(__METHOD__.' est déprécié. Utiliser Database::get()', E_USER_DEPRECATED);
|
|
return self::get();
|
|
}
|
|
|
|
/** @deprecated Utiliser Database::get() */
|
|
public static function getPdo(): PDO
|
|
{
|
|
@trigger_error(__METHOD__.' est déprécié. Utiliser Database::get()', E_USER_DEPRECATED);
|
|
return self::get();
|
|
}
|
|
|
|
/** @deprecated Utiliser Database::get() */
|
|
public static function getInstance(): PDO
|
|
{
|
|
@trigger_error(__METHOD__.' est déprécié. Utiliser Database::get()', E_USER_DEPRECATED);
|
|
return self::get();
|
|
}
|
|
|
|
public static function transactional(callable $fn)
|
|
{
|
|
$pdo = self::get();
|
|
try {
|
|
$pdo->beginTransaction();
|
|
$ret = $fn($pdo);
|
|
$pdo->commit();
|
|
return $ret;
|
|
} catch (\Throwable $e) {
|
|
if ($pdo->inTransaction()) {
|
|
$pdo->rollBack();
|
|
}
|
|
throw $e;
|
|
}
|
|
}
|
|
}
|