ContredanseDb::getPassword()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Infra\Db;
6
7
use App\Exception\ConnectionException;
8
9
class ContredanseDb
10
{
11
    /**
12
     * @var \PDO
13
     */
14
    private $pdo;
15
16
    /**
17
     * @var array
18
     */
19
    private $params;
20
21
    public function __construct(array $params)
22
    {
23
        $this->params = $params;
24
    }
25
26
    /**
27
     * @throws ConnectionException
28
     */
29
    public function getPdoAdapter(): \PDO
30
    {
31
        if ($this->pdo === null) {
32
            $this->pdo = $this->createPdoConnection($this->params);
33
        }
34
35
        return $this->pdo;
36
    }
37
38
    /**
39
     * @param string[] $config
40
     *
41
     * @throws ConnectionException
42
     */
43
    public function createPdoConnection(array $config): \PDO
44
    {
45
        $dsn = $this->getDsn();
46
47
        /** @var string[] $options */
48
        $options = $config['driver_options'] ?? null;
49
50
        try {
51
            $pdo = new \PDO($dsn, $config['username'], $config['password'], $options);
52
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
53
        } catch (\Throwable $e) {
54
            throw new ConnectionException(sprintf(
55
                'Database connection failure (%s)',
56
                $e->getMessage()
57
            ));
58
        }
59
60
        return $pdo;
61
    }
62
63
    public function getDsn(): string
64
    {
65
        return sprintf(
66
            '%s:host=%s;dbname=%s;port=%s',
67
            $this->params['driver'],
68
            $this->params['host'],
69
            $this->params['dbname'],
70
            $this->params['port']
71
        );
72
    }
73
74
    public function getUsername(): string
75
    {
76
        return $this->params['username'];
77
    }
78
79
    public function getPassword(): string
80
    {
81
        return $this->params['password'];
82
    }
83
84
    public function getConnectionInfo(): array
85
    {
86
        return [
87
            'username' => $this->params['username'],
88
            'password' => $this->params['password'],
89
            'host'     => $this->params['host'],
90
            'dbname'   => $this->params['dbname'],
91
            'port'     => $this->params['port'],
92
        ];
93
    }
94
}
95