Dsn   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 26
c 1
b 0
f 0
dl 0
loc 71
ccs 26
cts 26
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C parse() 0 48 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Bdf\Dsn;
6
7
use Bdf\Dsn\Exception\InvalidFormatException;
8
9
/**
10
 * Dsn
11
 * 
12
 * a dsn parser
13
 */
14
final class Dsn
15
{
16
    /**
17
     * Returns the Data Source Name as a structure containing the various parts of the DSN.
18
     *
19
     * Additional keys can be added by appending a URI query string to the end of the DSN.
20
     *
21
     * The allowed formats:
22
     * <code>
23
     *  scheme://user:password@host/path?foo=bar
24
     *  scheme://user:password@host
25
     *  scheme://user@host
26
     *  scheme://host/path
27
     *  scheme://host
28
     *  scheme:var1=value1;var2=value2
29
     *  scheme:path
30
     *  scheme
31
     * </code>
32
     *
33
     * @param string $dsn Data Source Name to be parsed
34
     *
35
     * @return DsnRequest
36
     */
37 11
    public static function parse(string $dsn): DsnRequest
38
    {
39
        // Only parsing dsn as url
40 11
        if (false === strpos($dsn, ':')) {
41 1
            return new DsnRequest($dsn, $dsn);
42
        }
43
44 10
        $url = parse_url($dsn);
45
46 10
        if (false === $url) {
47 1
            throw new InvalidFormatException('Invalid DSN.');
48
        }
49
50 9
        $url = array_map('rawurldecode', $url);
51
52
        // Manage the "driver:var1=value1;var2=value2" synthax
53 9
        if (isset($url['path']) && !isset($url['query']) && false !== strpos($url['path'], ';')) {
54 1
            $url['query'] = str_replace(';', '&', $url['path']);
55 1
            unset($url['path']);
56
        }
57
58 9
        $request = new DsnRequest($dsn, $url['scheme']);
59
60
        // Parse the query string as additionnal options
61 9
        if (isset($url['query'])) {
62 5
            $query = [];
63 5
            parse_str($url['query'], $query);
64
65 5
            $request->setQuery($query);
66
        }
67
68 9
        if (isset($url['host'])) {
69 6
            $request->setHost($url['host']);
70
        }
71 9
        if (isset($url['port'])) {
72 1
            $request->setPort($url['port']);
73
        }
74 9
        if (isset($url['user'])) {
75 3
            $request->setUser($url['user']);
76
        }
77 9
        if (isset($url['pass'])) {
78 3
            $request->setPassword($url['pass']);
79
        }
80 9
        if (isset($url['path'])) {
81 8
            $request->setPath($url['path']);
82
        }
83
84 9
        return $request;
85
    }
86
}
87