Completed
Push — master ( d40022...a8a6e5 )
by Arne
01:50
created

PathUtils   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 0
dl 0
loc 63
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A expandTilde() 0 9 2
B getAbsolutePath() 0 37 6
1
<?php
2
3
namespace Archivr;
4
5
abstract class PathUtils
6
{
7
    /**
8
     * If a path relative to the user home is given this function expands the path to an absolute path.
9
     *
10
     * @param string $path
11
     * @return string
12
     */
13
    public static function expandTilde(string $path): string
14
    {
15
        if (substr($path, 0, 1) === '~')
16
        {
17
            $path = posix_getpwuid(posix_getuid())['dir'] . substr($path, 1);
18
        }
19
20
        return $path;
21
    }
22
23
    /**
24
     * Returns the absolute path without the need for the path actually existing.
25
     *
26
     * @see https://php.net/manual/en/function.realpath.php#84012
27
     * @param string $path
28
     * @return string
29
     */
30
    public static function getAbsolutePath(string $path): string
31
    {
32
        if (($expanded = static::expandTilde($path)) !== $path)
33
        {
34
            return $expanded;
35
        }
36
37
        $pathParts = array_filter(explode('/', $path), 'strlen');
38
        $absolutePathParts = [];
39
40
        foreach ($pathParts as $part)
41
        {
42
            if ('.' == $part)
43
            {
44
                continue;
45
            }
46
            if ('..' == $part)
47
            {
48
                array_pop($absolutePathParts);
49
            }
50
            else
51
            {
52
                $absolutePathParts[] = $part;
53
            }
54
        }
55
56
        $return = implode('/', $absolutePathParts);
57
58
        if (substr($path, 0, 1) === '/')
59
        {
60
            return '/' . $return;
61
        }
62
        else
63
        {
64
            return getcwd() . '/' . $return;
65
        }
66
    }
67
}
68