pdo-document/src/Configuration.php

68 lines
2.3 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use PDO;
/**
* Common configuration for the document library
*/
class Configuration
{
/** @var string The name of the ID field used in the database (will be treated as the primary key) */
public static string $idField = 'id';
/** @var string The data source name (DSN) of the connection string */
public static string $pdoDSN = '';
/** @var string|null The username to use to establish a data connection (use env PDO_DOC_USERNAME if possible) */
public static ?string $username = null;
/** @var string|null The password to use to establish a data connection (use env PDO_DOC_PASSWORD if possible) */
public static ?string $password = null;
/** @var array|null Options to use for connections (driver-specific) */
public static ?array $options = null;
/** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */
public static ?Mode $mode = null;
/** @var PDO|null The PDO instance to use for database commands */
private static ?PDO $_pdo = null;
/**
* Retrieve a new connection to the database
*
* @return PDO A new connection to the SQLite database with foreign key support enabled
* @throws DocumentException If this is called before a connection string is set
*/
public static function dbConn(): PDO
{
if (is_null(self::$_pdo)) {
if (empty(self::$pdoDSN)) {
throw new DocumentException('Please provide a data source name (DSN) before attempting data access');
}
self::$_pdo = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
if (is_null(self::$mode)) {
$driver = self::$_pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
self::$mode = match ($driver) {
'pgsql' => Mode::PgSQL,
'sqlite' => Mode::SQLite,
default => throw new DocumentException(
"Unsupported driver $driver: this library currently supports PostgreSQL and SQLite")
};
}
}
return self::$_pdo;
}
public static function resetPDO(): void
{
self::$_pdo = null;
}
}