1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cozy\Database\Relational\Configuration; |
6
|
|
|
|
7
|
|
|
use Cozy\Database\Relational\Connection; |
8
|
|
|
use Cozy\Database\Relational\Exception; |
9
|
|
|
|
10
|
|
|
class DSNConfiguration implements ConfigurationInterface |
11
|
|
|
{ |
12
|
|
|
private $dsn; |
13
|
|
|
private $username; |
14
|
|
|
private $password; |
15
|
|
|
private $options = [ |
16
|
|
|
\PDO::ATTR_TIMEOUT => 1, |
17
|
|
|
]; |
18
|
|
|
private $pdo; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Creates a configuration set representing a connection to a database. |
22
|
|
|
* |
23
|
|
|
* @param string $dsn The Data Source Name, or DSN, contains the information required to connect to the database. |
24
|
|
|
* @param string $username The user name for the DSN string. This parameter is optional for some PDO drivers. |
25
|
|
|
* @param string $password The password for the DSN string. This parameter is optional for some PDO drivers. |
26
|
|
|
* @param array $options A key=>value array of PDO driver-specific connection options. |
27
|
|
|
*/ |
28
|
|
|
public function __construct(string $dsn, string $username, string $password, array $options = []) |
29
|
|
|
{ |
30
|
|
|
$this->dsn = $dsn; |
31
|
|
|
$this->username = $username; |
32
|
|
|
$this->password = $password; |
33
|
|
|
$this->options = array_merge($this->options, $options); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function isValid(): bool |
37
|
|
|
{ |
38
|
|
|
try { |
39
|
|
|
$this->pdo = new \PDO($this->dsn, $this->username, $this->password, $this->options); |
40
|
|
|
return true; |
41
|
|
|
} catch (\PDOException $e) { |
42
|
|
|
return false; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function buildConnection(): Connection |
47
|
|
|
{ |
48
|
|
|
try { |
49
|
|
|
if (!isset($this->pdo) || !($this->pdo instanceof \PDO)) { |
50
|
|
|
$this->pdo = new \PDO($this->dsn, $this->username, $this->password, $this->options); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return new Connection($this->pdo); |
54
|
|
|
} catch (\PDOException $e) { |
55
|
|
|
throw new Exception($e->getMessage(), $e->getCode(), $e->errorInfo); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|