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

ConnectionLocatorFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 31
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A changeHost() 0 10 2
A __construct() 0 2 1
A newInstance() 0 13 2
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