Passed
Push — master ( a109d5...60699f )
by Alexander
14:49
created

Dsn::getDriver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Connection;
6
7
final class Dsn
8
{
9
    private ?string $databaseName;
10
    private string $driver;
11
    private ?string $host;
12
    private ?string $port;
13
    private array $options;
14
15
    public function __construct(string $driver, string $host, string $databaseName, string $port = null, array $options = [])
16
    {
17
        $this->driver = $driver;
18
        $this->host = $host;
19
        $this->databaseName = $databaseName;
20
        $this->port = $port;
21
        $this->options = $options;
22
    }
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
    public function asString(): string
40
    {
41
        $dsn = "$this->driver:" . "host=$this->host" . ';' . "dbname=$this->databaseName";
42
43
        if ($this->port !== null) {
44
            $dsn .= ';' . "port=$this->port";
45
        }
46
47
        $parts = [];
48
49
        foreach ($this->options as $key => $value) {
50
            $parts[] = "$key=$value";
51
        }
52
53
        if (!empty($parts)) {
54
            $dsn .= ';' . implode(';', $parts);
55
        }
56
57
        return $dsn;
58
    }
59
60
    public function __toString(): string
61
    {
62
        return $this->asString();
63
    }
64
65
    public function getDriver(): string
66
    {
67
        return $this->driver;
68
    }
69
}
70