Passed
Push — env_slave ( 209401...a161d4 )
by Akihito
01:37
created

NamedPdoModule::changeHost()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\AuraSqlModule;
6
7
use Aura\Sql\ExtendedPdo;
8
use Aura\Sql\ExtendedPdoInterface;
9
use Ray\Di\AbstractModule;
10
11
class NamedPdoModule extends AbstractModule
12
{
13
    public const PARSE_PDO_DSN_REGEX = '/(.*?)\:(host|server)=.*?;(.*)/i';
14
15
    private string $qualifer;
16
    private string $dsn;
17
    private string $user;
18
    private string $password;
19
    private string $slave;
20
21
    public function __construct(
22
        string $qualifer,
23
        string $dsn,
24
        string $user = '',
25
        string $pass = '',
26
        string $slave = ''
27
    ) {
28
        $this->qualifer = $qualifer;
29
        $this->dsn = $dsn;
30
        $this->user = $user;
31
        $this->password = $pass;
32
        $this->slave = $slave;
33
        parent::__construct();
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    protected function configure(): void
40
    {
41
        $this->slave ? $this->configureMasterSlaveDsn($this->qualifer, $this->dsn, $this->user, $this->password, $this->slave)
42
            : $this->configureSingleDsn($this->qualifer, $this->dsn, $this->user, $this->password);
43
    }
44
45
    private function configureSingleDsn(string $qualifer, string $dsn, string $user, string $password): void
46
    {
47
        $this->bind(ExtendedPdoInterface::class)
48
            ->annotatedWith($qualifer)
49
            ->toConstructor(
50
                ExtendedPdo::class,
51
                "dsn={$qualifer}_dsn,username={$qualifer}_username,password={$qualifer}_password"
52
            );
53
        $this->bind()->annotatedWith("{$qualifer}_dsn")->toInstance($dsn);
54
        $this->bind()->annotatedWith("{$qualifer}_username")->toInstance($user);
55
        $this->bind()->annotatedWith("{$qualifer}_password")->toInstance($password);
56
    }
57
58
    private function configureMasterSlaveDsn(string $qualifer, string $dsn, string $user, string $password, string $slaveList): void
59
    {
60
        $locator = ConnectionLocatorFactory::newInstance($dsn, $user, $password, $slaveList);
61
        $this->install(new AuraSqlReplicationModule($locator, $qualifer));
62
    }
63
}
64