-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathTestTrait.php
118 lines (94 loc) · 2.81 KB
/
TestTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Pgsql\Tests\Support;
use Yiisoft\Db\Driver\Pdo\PdoConnectionInterface;
use Yiisoft\Db\Driver\Pdo\PdoDriverInterface;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Pgsql\Connection;
use Yiisoft\Db\Pgsql\Driver;
use Yiisoft\Db\Pgsql\Dsn;
use Yiisoft\Db\Tests\Support\DbHelper;
trait TestTrait
{
private string $dsn = '';
private string $fixture = 'pgsql.sql';
/**
* @throws InvalidConfigException
* @throws Exception
*/
protected function getConnection(bool $fixture = false): PdoConnectionInterface
{
$db = new Connection($this->getDriver(), DbHelper::getSchemaCache());
if ($fixture) {
DbHelper::loadFixture($db, __DIR__ . "/Fixture/$this->fixture");
}
return $db;
}
protected static function getDb(): PdoConnectionInterface
{
$dsn = (new Dsn(
host: self::getHost(),
databaseName: self::getDatabaseName(),
port: self::getPort(),
))->asString();
$driver = new Driver($dsn, self::getUsername(), self::getPassword());
$driver->charset('utf8');
return new Connection($driver, DbHelper::getSchemaCache());
}
protected function getDsn(): string
{
if ($this->dsn === '') {
$this->dsn = (new Dsn(
host: self::getHost(),
databaseName: self::getDatabaseName(),
port: self::getPort(),
))->asString();
}
return $this->dsn;
}
protected function getDriverName(): string
{
return 'pgsql';
}
protected function setDsn(string $dsn): void
{
$this->dsn = $dsn;
}
protected function setFixture(string $fixture): void
{
$this->fixture = $fixture;
}
public static function setUpBeforeClass(): void
{
$db = self::getDb();
DbHelper::loadFixture($db, __DIR__ . '/Fixture/pgsql.sql');
$db->close();
}
protected function getDriver(): PdoDriverInterface
{
$driver = new Driver($this->getDsn(), self::getUsername(), self::getPassword());
$driver->charset('utf8');
return $driver;
}
private static function getDatabaseName(): string
{
return getenv('YII_PGSQL_DATABASE') ?: 'yiitest';
}
private static function getHost(): string
{
return getenv('YII_PGSQL_HOST') ?: '127.0.0.1';
}
private static function getPort(): string
{
return getenv('YII_PGSQL_PORT') ?: '5432';
}
private static function getUsername(): string
{
return getenv('YII_PGSQL_USER') ?: 'root';
}
private static function getPassword(): string
{
return getenv('YII_PGSQL_PASSWORD') ?: 'root';
}
}