Skip to content

Commit 330c0e1

Browse files
authored
Allow dynamic connection (#835)
* Allow dynamic connection * Add test case.
1 parent 7eb17fa commit 330c0e1

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

src/Migration/ManagerFactory.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,16 @@ public function createConfig(): ConfigInterface
8888
$templatePath = dirname(__DIR__) . DS . 'templates' . DS;
8989
$connectionName = (string)$this->getOption('connection');
9090

91-
$connectionConfig = ConnectionManager::getConfig($connectionName);
91+
if (str_contains($connectionName, '://')) {
92+
/** @var array<string, mixed> $connectionConfig */
93+
$connectionConfig = ConnectionManager::parseDsn($connectionName);
94+
$connectionName = 'tmp';
95+
if (!ConnectionManager::getConfig($connectionName)) {
96+
ConnectionManager::setConfig($connectionName, $connectionConfig);
97+
}
98+
} else {
99+
$connectionConfig = ConnectionManager::getConfig($connectionName);
100+
}
92101
if (!$connectionConfig) {
93102
throw new RuntimeException("Could not find connection `{$connectionName}`");
94103
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace Migrations\Test\TestCase\Migration;
5+
6+
use Cake\Console\ConsoleIo;
7+
use Cake\Console\TestSuite\StubConsoleInput;
8+
use Cake\Console\TestSuite\StubConsoleOutput;
9+
use Cake\Datasource\ConnectionManager;
10+
use Migrations\Migration\ManagerFactory;
11+
use PHPUnit\Framework\TestCase;
12+
13+
class ManagerFactoryTest extends TestCase
14+
{
15+
public function testConnection(): void
16+
{
17+
$this->out = new StubConsoleOutput();
18+
$this->out->setOutputAs(StubConsoleOutput::PLAIN);
19+
$this->in = new StubConsoleInput([]);
20+
21+
$io = new ConsoleIo($this->out, $this->out, $this->in);
22+
23+
$factory = new ManagerFactory(['connection' => 'test']);
24+
$result = $factory->createManager($io);
25+
26+
$this->assertSame('test', $result->getConfig()->getConnection());
27+
}
28+
29+
public function testDsnConnection(): void
30+
{
31+
$this->out = new StubConsoleOutput();
32+
$this->out->setOutputAs(StubConsoleOutput::PLAIN);
33+
$this->in = new StubConsoleInput([]);
34+
35+
$io = new ConsoleIo($this->out, $this->out, $this->in);
36+
37+
$factory = new ManagerFactory(['connection' => 'mysql://root@127.0.0.1/db_tmp']);
38+
$result = $factory->createManager($io);
39+
40+
$this->assertSame('tmp', $result->getConfig()->getConnection());
41+
$expected = [
42+
'scheme' => 'mysql',
43+
'username' => 'root',
44+
'host' => '127.0.0.1',
45+
'className' => 'Cake\Database\Connection',
46+
'database' => 'db_tmp',
47+
'driver' => 'Cake\Database\Driver\Mysql',
48+
'name' => 'tmp',
49+
];
50+
$this->assertEquals($expected, ConnectionManager::getConfig('tmp'));
51+
}
52+
}

0 commit comments

Comments
 (0)