AbstractDsnSocket   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 72
rs 10
wmc 11

7 Methods

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