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

Dsn   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
dl 0
loc 56
ccs 17
cts 19
cp 0.8947
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A getDsn() 0 19 4
A getDriver() 0 3 1
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