DataSourceName::read()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 10
ccs 0
cts 5
cp 0
crap 6
rs 10
1
<?php
2
3
/**
4
 * This file is part of Cycle Database package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\Database\Config\Support;
13
14
/**
15
 * @internal Cycle\Database\Config\Support\DataSourceName is an internal library class,
16
 * please do not use it in your code.
17
 *
18
 * @psalm-internal Cycle\Database\Config
19
 */
20
final class DataSourceName
21
{
22
    /**
23
     * @param non-empty-string $dsn
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
24
     * @param non-empty-string $name
25
     *
26
     * @return non-empty-string
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
27
     */
28
    public static function normalize(string $dsn, string $name): string
29
    {
30
        if (!\str_starts_with($dsn, "$name:")) {
31
            $dsn = "$name:$dsn";
32
        }
33
34
        return $dsn;
35
    }
36
37
    /**
38
     * @param non-empty-string $haystack
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
39
     * @param array<non-empty-string>|non-empty-string $needle
40
     *
41
     * @return non-empty-string|null
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string|null at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string|null.
Loading history...
42
     */
43
    public static function read(string $haystack, array|string $needle): ?string
44
    {
45
        $needle = \array_map(static fn(string $item): string => \preg_quote($item), (array) $needle);
46
        $pattern = \sprintf('/\b(?:%s)=([^;]+)/i', \implode('|', $needle));
47
48
        if (\preg_match($pattern, $haystack, $matches)) {
49
            return $matches[1];
50
        }
51
52
        return null;
53
    }
54
}
55