1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Connection; |
6
|
|
|
|
7
|
|
|
use Stringable; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* The Dsn class is typically used to parse a DSN string, which is a string that contains all the necessary information |
11
|
|
|
* to connect to a database, such as the database driver, unix socket, database name, options. |
12
|
|
|
* |
13
|
|
|
* It also allows you to access individual components of the DSN, such as the driver or the database name. |
14
|
|
|
*/ |
15
|
|
|
abstract class AbstractDsnSocket implements DsnInterface, Stringable |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @psalm-param string[] $options |
19
|
|
|
*/ |
20
|
|
|
public function __construct( |
21
|
|
|
private string $driver, |
22
|
|
|
private string $unixSocket, |
23
|
|
|
private string $databaseName, |
24
|
|
|
private array $options = [] |
25
|
|
|
) { |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function asString(): string |
29
|
|
|
{ |
30
|
|
|
$dsn = "$this->driver:" . "unix_socket=$this->unixSocket" . ';' . "dbname=$this->databaseName"; |
31
|
|
|
|
32
|
|
|
$parts = []; |
33
|
|
|
|
34
|
|
|
foreach ($this->options as $key => $value) { |
35
|
|
|
$parts[] = "$key=$value"; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if (!empty($parts)) { |
39
|
|
|
$dsn .= ';' . implode(';', $parts); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return $dsn; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @return string The Data Source Name, or DSN, contains the information required to connect to the database. |
47
|
|
|
*/ |
48
|
|
|
public function __toString(): string |
49
|
|
|
{ |
50
|
|
|
return $this->asString(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @return string The database name to connect to. |
55
|
|
|
*/ |
56
|
|
|
public function getDatabaseName(): string |
57
|
|
|
{ |
58
|
|
|
return $this->databaseName; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return string The database driver to use. |
63
|
|
|
*/ |
64
|
|
|
public function getDriver(): string |
65
|
|
|
{ |
66
|
|
|
return $this->driver; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return string The unix socket to connect to. |
71
|
|
|
*/ |
72
|
|
|
public function getUnixSocket(): string |
73
|
|
|
{ |
74
|
|
|
return $this->unixSocket; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return array The options to use. |
79
|
|
|
*/ |
80
|
|
|
public function getOptions(): array |
81
|
|
|
{ |
82
|
|
|
return $this->options; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|