Passed
Push — master ( 3d4557...4c2a8d )
by Hannes
01:54
created

NameObj::getShortName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace hanneskod\readmetester\Utils;
6
7
class NameObj
8
{
9
    public const NAMESPACE_DELIMITER = ':';
10
11
    private const INVALID_CHAR_REGEXP = "/[^a-z0-9.\\/_-]/i";
12
13
    private string $namespace;
14
    private string $shortName;
15
16
    public static function fromString(string $name, string $defaultNamespace = ''): self
17
    {
18
        $parts = explode(self::NAMESPACE_DELIMITER, $name, 2);
19
20
        $namespaceGiven = isset($parts[1]) && $parts[1];
21
22
        return new self(
23
            $namespaceGiven ? $parts[0] : $defaultNamespace,
24
            $namespaceGiven ? $parts[1] : $parts[0]
25
        );
26
    }
27
28
    public function __construct(string $namespace, string $shortName)
29
    {
30
        $this->namespace = self::sanitizeName($namespace);
31
        $this->shortName = self::sanitizeName($shortName);
32
    }
33
34
    public function getFullName(): string
35
    {
36
        return $this->getNamespaceName()
37
            ? $this->getNamespaceName() . self::NAMESPACE_DELIMITER . $this->getShortName()
38
            : $this->getShortName();
39
    }
40
41
    public function getShortName(): string
42
    {
43
        return $this->shortName;
44
    }
45
46
    public function getNamespaceName(): string
47
    {
48
        return $this->namespace;
49
    }
50
51
    private static function sanitizeName(string $name): string
52
    {
53
        return (string)preg_replace(
54
            self::INVALID_CHAR_REGEXP,
55
            '',
56
            str_replace(' ', '-', $name)
57
        );
58
    }
59
}
60