Passed
Pull Request — master (#24)
by Dmitriy
37:45 queued 22:43
created

PathHelper::realpath()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 16
rs 9.9332
c 0
b 0
f 0
cc 4
nc 4
nop 1
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
     * @return string
15
     */
16
    public static function realpath(string $path): string
17
    {
18
        $parts = explode('/', self::normalize($path));
19
        $out = [];
20
        foreach ($parts as $part) {
21
            if ($part === '.') {
22
                continue;
23
            }
24
            if ($part === '..') {
25
                array_pop($out);
26
                continue;
27
            }
28
            $out[] = $part;
29
        }
30
31
        return implode('/', $out);
32
    }
33
34
    public static function normalize(string $path): string
35
    {
36
        $search = ['//', '\\\\', '\\'];
37
        $replace = ['/', '\\', '/'];
38
        while (($processedPath = str_replace($search, $replace, $path)) !== $path) {
39
            $path = $processedPath;
40
        }
41
42
        return rtrim($path, '/');
43
    }
44
}
45