1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ray\AuraSqlModule; |
6
|
|
|
|
7
|
|
|
use Aura\Sql\ConnectionLocator; |
8
|
|
|
|
9
|
|
|
use function explode; |
10
|
|
|
use function preg_match; |
11
|
|
|
use function sprintf; |
12
|
|
|
|
13
|
|
|
final class ConnectionLocatorFactory |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @codeCoverageIgnore |
17
|
|
|
*/ |
18
|
|
|
private function __construct() |
19
|
|
|
{ |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param array<string> $options |
24
|
|
|
* @param array<string> $queries |
25
|
|
|
*/ |
26
|
|
|
public static function fromInstance( |
27
|
|
|
string $dsn, |
28
|
|
|
string $user, |
29
|
|
|
string $password, |
30
|
|
|
string $slave, |
31
|
|
|
array $options, |
32
|
|
|
array $queries |
33
|
|
|
): ConnectionLocator { |
34
|
|
|
$writes = ['master' => new Connection($dsn, $user, $password, $options, $queries)]; |
35
|
|
|
$i = 1; |
36
|
|
|
$slaves = explode(',', $slave); |
37
|
|
|
$reads = []; |
38
|
|
|
foreach ($slaves as $host) { |
39
|
|
|
$slaveDsn = self::changeHost($dsn, $host); |
40
|
|
|
$name = 'slave' . (string) $i++; |
41
|
|
|
$reads[$name] = new Connection($slaveDsn, $user, $password, $options, $queries); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return new ConnectionLocator(null, $reads, $writes); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param array<string> $options |
49
|
|
|
* @param array<string> $queries |
50
|
|
|
*/ |
51
|
|
|
public static function fromEnv( |
52
|
|
|
string $dsn, |
53
|
|
|
string $username, |
54
|
|
|
string $password, |
55
|
|
|
string $slave, |
56
|
|
|
array $options, |
57
|
|
|
array $queries |
58
|
|
|
): ConnectionLocator { |
59
|
|
|
$writes = ['master' => new EnvConnection($dsn, null, $username, $password, $options, $queries)]; |
60
|
|
|
$reads = ['slave' => new EnvConnection($dsn, $slave, $username, $password, $options, $queries)]; |
61
|
|
|
|
62
|
|
|
return new ConnectionLocator(null, $reads, $writes); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private static function changeHost(string $dsn, string $host): string |
66
|
|
|
{ |
67
|
|
|
preg_match(AuraSqlModule::PARSE_PDO_DSN_REGEX, $dsn, $parts); |
68
|
|
|
if (! $parts) { |
69
|
|
|
// @codeCoverageIgnoreStart |
70
|
|
|
return $dsn; |
71
|
|
|
// @codeCoverageIgnoreEnd |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return sprintf('%s:%s=%s;%s', $parts[1], $parts[2], $host, $parts[3]); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|