Initial SQLite development (#1)
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
67
src/Configuration.php
Normal file
67
src/Configuration.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user