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

PathHelper::realpath()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 16
ccs 10
cts 11
cp 0.9091
rs 9.9332
cc 4
nc 4
nop 1
crap 4.0119
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