Passed
Push — master ( cd14ff...da2bd7 )
by Alexander
03:37 queued 25s
created

PathHelper::normalize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config\Util;
6
7
final class PathHelper
8
{
9
    /**
10
     * PHP implementation of {@see realpath()} method returns `false` when file or directory does not exist.
11
     * This method prevents this behavior.
12
     *
13
     * @param string $path
14
     *
15
     * @return string
16
     */
17 12
    public static function realpath(string $path): string
18
    {
19 12
        $parts = explode('/', self::normalize($path));
20 12
        $out = [];
21 12
        foreach ($parts as $part) {
22 12
            if ($part === '.') {
23
                continue;
24
            }
25 12
            if ($part === '..') {
26 8
                array_pop($out);
27 8
                continue;
28
            }
29 12
            $out[] = $part;
30
        }
31
32 12
        return implode('/', $out);
33
    }
34
35 20
    public static function normalize(string $path): string
36
    {
37 20
        $search = ['//', '\\\\', '\\'];
38 20
        $replace = ['/', '\\', '/'];
39 20
        while (($processedPath = str_replace($search, $replace, $path)) !== $path) {
40 14
            $path = $processedPath;
41
        }
42
43 20
        return rtrim($path, '/');
44
    }
45
}
46