|
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
|
|
|
private $params; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(array $params) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->params = $params; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @throws ConnectionException |
|
25
|
|
|
*/ |
|
26
|
|
|
public function getPdoAdapter(): \PDO |
|
27
|
|
|
{ |
|
28
|
|
|
if ($this->pdo === null) { |
|
29
|
|
|
$this->pdo = $this->createPdoConnection($this->params); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
return $this->pdo; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param string[] $config |
|
37
|
|
|
* |
|
38
|
|
|
* @throws ConnectionException |
|
39
|
|
|
*/ |
|
40
|
|
|
public function createPdoConnection(array $config): \PDO |
|
41
|
|
|
{ |
|
42
|
|
|
$dsn = $this->getDsn(); |
|
43
|
|
|
|
|
44
|
|
|
/** @var string[] $options */ |
|
45
|
|
|
$options = $config['driver_options'] ?? null; |
|
46
|
|
|
|
|
47
|
|
|
try { |
|
48
|
|
|
$pdo = new \PDO($dsn, $config['username'], $config['password'], $options); |
|
49
|
|
|
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); |
|
50
|
|
|
} catch (\Throwable $e) { |
|
51
|
|
|
throw new ConnectionException(sprintf( |
|
52
|
|
|
'Database connection failure (%s)', |
|
53
|
|
|
$e->getMessage() |
|
54
|
|
|
)); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $pdo; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function getDsn(): string |
|
61
|
|
|
{ |
|
62
|
|
|
return sprintf( |
|
63
|
|
|
'%s:host=%s;dbname=%s;port=%s', |
|
64
|
|
|
$this->params['driver'], |
|
65
|
|
|
$this->params['host'], |
|
66
|
|
|
$this->params['dbname'], |
|
67
|
|
|
$this->params['port'] |
|
68
|
|
|
); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function getUsername(): string |
|
72
|
|
|
{ |
|
73
|
|
|
return $this->params['username']; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
public function getPassword(): string |
|
77
|
|
|
{ |
|
78
|
|
|
return $this->params['password']; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
public function getConnectionInfo(): array |
|
82
|
|
|
{ |
|
83
|
|
|
return [ |
|
84
|
|
|
'username' => $this->params['username'], |
|
85
|
|
|
'password' => $this->params['password'], |
|
86
|
|
|
'host' => $this->params['host'], |
|
87
|
|
|
'dbname' => $this->params['dbname'], |
|
88
|
|
|
'port' => $this->params['port'], |
|
89
|
|
|
]; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|