Daniel J. Summers
330e272187
- Change multiple field matching to enum - Implement auto-generated IDs Reviewed-on: #2
78 lines
2.7 KiB
PHP
78 lines
2.7 KiB
PHP
<?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 AutoId The automatic ID generation process to use */
|
|
public static AutoId $autoId = AutoId::None;
|
|
|
|
/**
|
|
* @var int The number of characters a string generated by `AutoId::RandomString` will have (must be an even number)
|
|
*/
|
|
public static int $idStringLength = 16;
|
|
|
|
/** @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;
|
|
}
|
|
|
|
/**
|
|
* Clear the current PDO instance
|
|
*/
|
|
public static function resetPDO(): void
|
|
{
|
|
self::$_pdo = null;
|
|
}
|
|
}
|