diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 26e443e..6630150 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -49,6 +49,7 @@ Yii Framework 2 Change Log - Chg #15481: Removed `yii\BaseYii::powered()` method (Kolyunya, samdark) - Chg #15811: Fixed issue with additional parameters on `yii\base\View::renderDynamic()` while parameters contains single quote introduced in #12938 (xicond) - Enh #16054: Callback execution with mutex synchronization (zhuravljov) +- Enh #16126: Allows to configure `Connection::dsn` by config array (leandrogehlen) 2.0.14.2 under development ------------------------ diff --git a/framework/db/Connection.php b/framework/db/Connection.php index 09a3548..a1694df 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -426,6 +426,15 @@ class Connection extends Component */ private $_queryCacheInfo = []; + /** + * {@inheritdoc} + */ + public function init() + { + if (is_array($this->dsn)) { + $this->dsn = $this->buildDSN($this->dsn); + } + } /** * Returns a value indicating whether the DB connection is established. @@ -1111,6 +1120,29 @@ class Connection extends Component } /** + * Build the Data Source Name or DSN + * @param array $config the DSN configurations + * @return string the formated DSN + * @throws InvalidConfigException if 'driver' key was not defined + */ + private function buildDSN(array $config) + { + if (isset($config['driver'])) { + $parts = []; + $driver = $config['driver']; + unset($config['driver']); + + foreach ($config as $key => $value) { + $parts[] = "$key=$value"; + } + + return "$driver:" . implode(';', $parts); + } else { + throw new InvalidConfigException("Connection 'driver' must be set."); + } + } + + /** * Close the connection before serializing. * @return array */ diff --git a/tests/framework/db/ConnectionTest.php b/tests/framework/db/ConnectionTest.php index e347f11..11b507c 100644 --- a/tests/framework/db/ConnectionTest.php +++ b/tests/framework/db/ConnectionTest.php @@ -434,4 +434,20 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertNotNull($slavePdo); $this->assertNotSame($masterPdo, $slavePdo); } + + public function testDSNConfig() + { + $dsn = [ + 'driver' => 'mysql', + 'host' => '127.0.0.1', + 'dbname' => 'yiitest' + ]; + + $connection = new Connection(['dsn' => $dsn]); + $this->assertEquals('mysql:host=127.0.0.1;dbname=yiitest', $connection->dsn); + + unset($dsn['driver']); + $this->expectException('yii\base\InvalidConfigException'); + $connection = new Connection(['dsn' => $dsn]); + } }