Passed
Push — master ( d7b91e...70f900 )
by Def
15:34 queued 12:37
created

Dsn::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 1
cts 1
cp 1
cc 1
nc 1
nop 5
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Connection;
6
7
final class Dsn
8
{
9
    public function __construct(
10
        private string $driver,
11
        private string $host,
12
        private string $databaseName,
13
        private ?string $port = null,
14
        private array $options = []
15 956
    ) {
16
    }
17 956
18 956
    /**
19 956
     * @return string the Data Source Name, or DSN, contains the information required to connect to the database.
20 956
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.construct.php) on the format of the DSN string.
21 956
     *
22 956
     * The `driver` array key is used as the driver prefix of the DSN, all further key-value pairs are rendered as
23
     * `key=value` and concatenated by `;`. For example:
24
     *
25
     * ```php
26
     * $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
27
     * $connection = new Connection($this->cache, $this->logger, $this->profiler, $dsn->getDsn());
28
     * ```
29
     *
30
     * Will result in the DSN string `mysql:host=127.0.0.1;dbname=yiitest;port=3306`.
31
     */
32
    public function asString(): string
33
    {
34
        $dsn = "$this->driver:" . "host=$this->host" . ';' . "dbname=$this->databaseName";
35
36
        if ($this->port !== null) {
37
            $dsn .= ';' . "port=$this->port";
38 956
        }
39
40 956
        $parts = [];
41
42 956
        /** @psalm-var string[] */
43 956
        $options = $this->options;
44
45
        foreach ($options as $key => $value) {
46 956
            $parts[] = "$key=$value";
47
        }
48 956
49
        if (!empty($parts)) {
50
            $dsn .= ';' . implode(';', $parts);
51
        }
52 956
53
        return $dsn;
54
    }
55
56 956
    public function __toString(): string
57
    {
58
        return $this->asString();
59
    }
60
61
    public function getDatabaseName(): string
62
    {
63
        return $this->databaseName;
64
    }
65
66
    public function getDriver(): string
67
    {
68
        return $this->driver;
69
    }
70
71
    public function getHost(): string
72
    {
73
        return $this->host;
74
    }
75
76
    public function getPort(): ?string
77
    {
78
        return $this->port;
79
    }
80
}
81