Passed
Push — env_slave ( 209401 )
by Akihito
10:11
created

ConnectionLocatorFactory::newInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 4
dl 0
loc 13
rs 9.9666
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
    private function __construct()
16
    {
17
    }
18
19
    public static function newInstance(string $dsn, string $user, string $password, string $slave): ConnectionLocator
20
    {
21
        $writes = ['master' => new Connection($dsn, $user, $password)];
22
        $i = 1;
23
        $slaves = explode(',', $slave);
24
        $reads = [];
25
        foreach ($slaves as $host) {
26
            $slaveDsn = self::changeHost($dsn, $host);
27
            $name = 'slave' . (string) $i++;
28
            $reads[$name] = new Connection($slaveDsn, $user, $password);
29
        }
30
31
        return new ConnectionLocator(null, $reads, $writes);
32
    }
33
34
    private static function changeHost(string $dsn, string $host): string
35
    {
36
        preg_match(AuraSqlModule::PARSE_PDO_DSN_REGEX, $dsn, $parts);
37
        if (! $parts) {
38
            // @codeCoverageIgnoreStart
39
            return $dsn;
40
            // @codeCoverageIgnoreEnd
41
        }
42
43
        return sprintf('%s:%s=%s;%s', $parts[1], $parts[2], $host, $parts[3]);
44
    }
45
}
46