diff --git a/CHANGELOG.md b/CHANGELOG.md index ddb324cf..1c3cc900 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ - New #280: Realize `ColumnBuilder` class (@Tigrov) - Enh #281: Update according changes in `ColumnSchemaInterface` (@Tigrov) - New #282: Add `ColumnDefinitionBuilder` class (@Tigrov) +- Enh #283: Refactor `Dsn` class (@Tigrov) ## 1.3.0 March 21, 2024 diff --git a/src/Dsn.php b/src/Dsn.php index 38191676..ea0fdcf5 100644 --- a/src/Dsn.php +++ b/src/Dsn.php @@ -14,14 +14,14 @@ final class Dsn extends AbstractDsn { /** - * @psalm-param string[] $options + * @psalm-param array $options */ public function __construct( - private string $driver, - private string $host, - private string|null $databaseName = null, - private string $port = '1521', - private array $options = [] + string $driver = 'oci', + string $host = '127.0.0.1', + string|null $databaseName = null, + string $port = '1521', + array $options = [] ) { parent::__construct($driver, $host, $databaseName, $port, $options); } @@ -43,20 +43,20 @@ public function __construct( */ public function asString(): string { - if (!empty($this->databaseName)) { - $dsn = "$this->driver:" . "dbname=$this->host:$this->port/$this->databaseName"; - } else { - $dsn = "$this->driver:" . "dbname=$this->host:$this->port"; - } + $driver = $this->getDriver(); + $host = $this->getHost(); + $databaseName = $this->getDatabaseName(); + $port = $this->getPort(); + $options = $this->getOptions(); - $parts = []; + $dsn = "$driver:dbname=$host:$port"; - foreach ($this->options as $key => $value) { - $parts[] = "$key=$value"; + if (!empty($databaseName)) { + $dsn .= "/$databaseName"; } - if (!empty($parts)) { - $dsn .= ';' . implode(';', $parts); + foreach ($options as $key => $value) { + $dsn .= ";$key=$value"; } return $dsn; diff --git a/tests/Support/TestTrait.php b/tests/Support/TestTrait.php index 0d7e1df1..8d5c73d3 100644 --- a/tests/Support/TestTrait.php +++ b/tests/Support/TestTrait.php @@ -33,7 +33,7 @@ protected function getConnection(bool $fixture = false): PdoConnectionInterface protected static function getDb(): PdoConnectionInterface { - $dsn = (new Dsn('oci', 'localhost', 'XE', '1521', ['charset' => 'AL32UTF8']))->asString(); + $dsn = (new Dsn(databaseName: 'XE', options: ['charset' => 'AL32UTF8']))->asString(); return new Connection(new Driver($dsn, 'system', 'root'), DbHelper::getSchemaCache()); } @@ -41,7 +41,7 @@ protected static function getDb(): PdoConnectionInterface protected function getDsn(): string { if ($this->dsn === '') { - $this->dsn = (new Dsn('oci', 'localhost', 'XE', '1521', ['charset' => 'AL32UTF8']))->asString(); + $this->dsn = (new Dsn(databaseName: 'XE', options: ['charset' => 'AL32UTF8']))->asString(); } return $this->dsn;