Passed
Push — master ( 9f7d35...3f1c7e )
by Wilmer
08:50 queued 06:32
created

Dsn::getDriver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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