Passed
Pull Request — 1.x (#69)
by Akihito
02:54 queued 01:30
created

ConnectionLocatorFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

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

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
    /**
16
     * @codeCoverageIgnore
17
     */
18
    private function __construct()
19
    {
20
    }
21
22
    public static function newInstance(string $dsn, string $user, string $password, string $slave): ConnectionLocator
23
    {
24
        $writes = ['master' => new Connection($dsn, $user, $password)];
25
        $i = 1;
26
        $slaves = explode(',', $slave);
27
        $reads = [];
28
        foreach ($slaves as $host) {
29
            $slaveDsn = self::changeHost($dsn, $host);
30
            $name = 'slave' . (string) $i++;
31
            $reads[$name] = new Connection($slaveDsn, $user, $password);
32
        }
33
34
        return new ConnectionLocator(null, $reads, $writes);
35
    }
36
37
    private static function changeHost(string $dsn, string $host): string
38
    {
39
        preg_match(AuraSqlModule::PARSE_PDO_DSN_REGEX, $dsn, $parts);
40
        if (! $parts) {
41
            // @codeCoverageIgnoreStart
42
            return $dsn;
43
            // @codeCoverageIgnoreEnd
44
        }
45
46
        return sprintf('%s:%s=%s;%s', $parts[1], $parts[2], $host, $parts[3]);
47
    }
48
}
49