66 lines
2.3 KiB
PHP
66 lines
2.3 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Modules\MiningChecker\Infrastructure;
|
|
|
|
use App\Database as AppDatabase;
|
|
use Modules\MiningChecker\Support\ApiException;
|
|
use PDO;
|
|
|
|
final class ConnectionFactory
|
|
{
|
|
public static function make(ModuleConfig $config): PDO
|
|
{
|
|
$moduleSettings = modules()->settings('mining-checker');
|
|
$useSeparateDb = self::usesSeparateDatabase($moduleSettings);
|
|
|
|
if ($useSeparateDb) {
|
|
$dbConfig = is_array($moduleSettings['db'] ?? null) ? $moduleSettings['db'] : [];
|
|
if ($dbConfig === []) {
|
|
throw new ApiException('Custom-Datenbank ist aktiviert, aber nicht vollstaendig konfiguriert.', 500);
|
|
}
|
|
self::assertSupportedDriver($dbConfig);
|
|
if (method_exists(AppDatabase::class, 'connectFromConfig')) {
|
|
return AppDatabase::connectFromConfig($dbConfig);
|
|
}
|
|
return AppDatabase::createFromArray($dbConfig);
|
|
}
|
|
|
|
$dbConfig = app()->config()->dbConfig;
|
|
if ($dbConfig === []) {
|
|
throw new ApiException('Projekt-Datenbankkonfiguration fehlt in config/db_settings_basic.php.', 500);
|
|
}
|
|
|
|
self::assertSupportedDriver($dbConfig);
|
|
|
|
if (method_exists(AppDatabase::class, 'connectFromConfig')) {
|
|
return AppDatabase::connectFromConfig($dbConfig);
|
|
}
|
|
|
|
return AppDatabase::createFromArray($dbConfig);
|
|
}
|
|
|
|
private static function usesSeparateDatabase(array $moduleSettings): bool
|
|
{
|
|
$raw = $moduleSettings['use_separate_db'] ?? false;
|
|
if (is_bool($raw)) {
|
|
return $raw;
|
|
}
|
|
|
|
$normalized = strtolower(trim((string) $raw));
|
|
return in_array($normalized, ['1', 'true', 'yes', 'on', 'custom'], true);
|
|
}
|
|
|
|
private static function assertSupportedDriver(array $dbConfig): void
|
|
{
|
|
$driver = strtolower((string) ($dbConfig['driver'] ?? ($dbConfig['dsn'] ?? '')));
|
|
if ($driver !== '' && !in_array($driver, ['mysql', 'pgsql'], true) && !str_starts_with($driver, 'mysql:') && !str_starts_with($driver, 'pgsql:')) {
|
|
throw new ApiException(
|
|
'Mining-Checker unterstuetzt aktuell MySQL/MariaDB und PostgreSQL. Stelle den Driver auf mysql oder pgsql.',
|
|
500,
|
|
['driver' => $dbConfig['driver'] ?? 'unknown']
|
|
);
|
|
}
|
|
}
|
|
}
|