Browse Source

Fixes #16126: Allows to configure `Connection::dsn` by config array

tags/3.0.0-alpha1
Leandro Gehlen 7 years ago committed by Alexander Makarov
parent
commit
b576336beb
  1. 1
      framework/CHANGELOG.md
  2. 32
      framework/db/Connection.php
  3. 16
      tests/framework/db/ConnectionTest.php

1
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
------------------------

32
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
*/

16
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]);
}
}

Loading…
Cancel
Save