Passed
Branch master (7a2f1a)
by Petr
03:10
created

TPathTransform::compactName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 14
ccs 11
cts 11
cp 1
rs 9.9
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace kalanis\kw_paths\Extras;
4
5
6
use kalanis\kw_paths\PathsException;
7
8
9
/**
10
 * trait TPathTransform
11
 * @package kalanis\kw_paths\Extras
12
 * Transform path from string to array and back
13
 */
14
trait TPathTransform
15
{
16
    /**
17
     * @param array<string> $path
18
     * @param string $pathDelimiter
19
     * @throws PathsException
20
     * @return string
21
     */
22 41
    public function compactName(array $path, string $pathDelimiter = DIRECTORY_SEPARATOR): string
23
    {
24 41
        if (empty($pathDelimiter)) {
25 1
            throw new PathsException($this->noDirectoryDelimiterSet());
26
        }
27 40
        return implode(
28 40
            $pathDelimiter,
29 40
            str_replace(
30 40
                $pathDelimiter,
31 40
                $this->getEscapeChar() . $pathDelimiter,
32 40
                str_replace(
33 40
                    $this->getEscapeChar(),
34 40
                    $this->getEscapeChar() . $this->getEscapeChar(),
35
                    $path
36
                )
37
            )
38
        );
39
    }
40
41
    /**
42
     * @param string $path
43
     * @param string $pathDelimiter
44
     * @throws PathsException
45
     * @return array<string>
46
     */
47 45
    public function expandName(string $path, string $pathDelimiter = DIRECTORY_SEPARATOR): array
48
    {
49 45
        $extraDelimiter = "--\e--";
50 45
        if (empty($pathDelimiter)) {
51 1
            throw new PathsException($this->noDirectoryDelimiterSet());
52
        }
53 44
        $path = str_replace($this->getEscapeChar() . $this->getEscapeChar(), $extraDelimiter . $extraDelimiter, $path);
54 44
        $path = str_replace($this->getEscapeChar() . $pathDelimiter, $this->getEscapeChar() . $extraDelimiter, $path);
55 44
        $arr = explode($pathDelimiter, $path);
56 44
        $arr = str_replace($this->getEscapeChar() . $extraDelimiter, $pathDelimiter, $arr);
57 44
        $arr = str_replace($extraDelimiter . $extraDelimiter, $this->getEscapeChar(), $arr);
58 44
        return $arr;
59
    }
60
61 45
    protected function getEscapeChar(): string
62
    {
63 45
        return '\\';
64
    }
65
66
    abstract protected function noDirectoryDelimiterSet(): string;
67
}
68