37 lines
1.2 KiB
PHP
37 lines
1.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Infrastructure;
|
|
|
|
use PDO;
|
|
|
|
final class DbAdapter
|
|
{
|
|
public static function pdo(): PDO
|
|
{
|
|
if (!empty($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
|
|
return $GLOBALS['pdo'];
|
|
}
|
|
$dsn = getenv('DB_DSN') ?: ($_ENV['DB_DSN'] ?? null);
|
|
$user = getenv('DB_USER') ?: ($_ENV['DB_USER'] ?? null);
|
|
$pass = getenv('DB_PASS') ?: ($_ENV['DB_PASS'] ?? null);
|
|
if (!$dsn) {
|
|
$host = getenv('DB_HOST') ?: ($_ENV['DB_HOST'] ?? 'localhost');
|
|
$port = getenv('DB_PORT') ?: ($_ENV['DB_PORT'] ?? '5432');
|
|
$name = getenv('DB_NAME') ?: ($_ENV['DB_NAME'] ?? null);
|
|
if ($name) {
|
|
$dsn = sprintf('pgsql:host=%s;port=%s;dbname=%s', $host, $port, $name);
|
|
}
|
|
}
|
|
if (!$dsn) {
|
|
throw new \RuntimeException('Aucun DSN pour initialiser PDO');
|
|
}
|
|
return 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,
|
|
]);
|
|
}
|
|
}
|