Skip to content

Commit

Permalink
added Factory::createFromParameters()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 29, 2024
1 parent 8cf9f96 commit 2258b45
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/Database/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ final class Factory
private const TypeConverterOptions = ['convertBoolean', 'convertDateTime', 'convertDecimal', 'newDateTime'];


public static function createFromParameters(
#[\SensitiveParameter]
...$params,
): Explorer
{
$params = count($params) === 1 && is_array($params[0] ?? null) ? $params[0] : $params;
$driver = self::createDriverFromParameters($params);
return self::createExplorer($driver, $params);
}


public static function createFromDsn(
string $dsn,
?string $username = null,
Expand All @@ -41,6 +52,36 @@ public static function createFromDsn(
}


private static function createDriverFromParameters(
#[\SensitiveParameter]
array $params,
): Drivers\Driver
{
if ($class = $params['driverClass'] ?? null) {
if (!is_subclass_of($class, Drivers\Driver::class)) {
throw new \LogicException("Driver class '$class' is not subclass of " . Drivers\Driver::class);
}
unset($params['driverClass']);

} elseif ($driver = $params['driver'] ?? null) {
$class = self::Drivers[$driver] ?? null;
if (!$class) {
throw new \LogicException("Unknown driver '$driver'.");
}
unset($params['driver']);

} elseif ($params['dsn'] ?? null) {
return self::createDriverFromDsn(...$params);

} else {
throw new \LogicException("Missing options 'driver' or 'driverClass'.");
}

$params = array_diff_key($params, array_flip(self::TypeConverterOptions));
return new $class($params);
}


private static function createDriverFromDsn(
string $dsn,
?string $username,
Expand Down

0 comments on commit 2258b45

Please sign in to comment.