Passed
Push — master ( c79db4...d48c3e )
by Vermeulen
41s queued 11s
created

Paths   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 61
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0
wmc 9

1 Method

Rating   Name   Duplication   Size   Complexity  
B absoluteToRelative() 0 51 9
1
<?php
2
3
namespace bultonFr\Utils\Files;
4
5
class Paths
6
{
7
    /**
8
     * Resolve the relative path for two abslute path
9
     *
10
     * @param string $srcPath
11
     * @param string $destPath
12
     *
13
     * @return string
14
     */
15
    public static function absoluteToRelative(
16
        string $srcPath,
17
        string $destPath
18
    ): string {
19 1
        if ($srcPath === $destPath) {
20 1
            return '';
21
        }
22
23
        //Remove first slash to not have a empty string for key 0
24
        //If path not start with slash, it's not an absolute path !
25 1
        $srcPathEx  = explode('/', substr($srcPath, 1));
26 1
        $destPathEx = explode('/', substr(dirname($destPath), 1));
27
28 1
        $samePathStatus = true;
29 1
        $notSameIdx     = 0;
30 1
        $relativePath   = '';
31 1
        $endSrcPath     = '';
32
33 1
        foreach ($srcPathEx as $srcIdx => $srcItem) {
34 1
            if ($samePathStatus === true) {
35
                //Always in the same path
36
                if (
37 1
                    isset($destPathEx[$srcIdx])
38 1
                    && $srcItem === $destPathEx[$srcIdx]
39
                ) {
40 1
                    continue;
41
                }
42
43 1
                $samePathStatus = false;
44 1
                $notSameIdx     = $srcIdx;
45
            }
46
47
            //Not the same path, so we add srcItem to the var which contain
48
            //end of relative path which will be returned.
49 1
            $endSrcPath .= (empty($endSrcPath)) ? '' : '/';
50 1
            $endSrcPath .= $srcItem;
51
        }
52
53
        //First item of paths is not same, no common between path.
54 1
        if ($notSameIdx === 0) {
55 1
            return $destPath;
56
        }
57
58 1
        $nbDestItem = count($destPathEx) - 1;
59 1
        for ($destIdx = $notSameIdx; $destIdx <= $nbDestItem; $destIdx++) {
60 1
            $relativePath .= '../';
61
        }
62
63 1
        $relativePath .= $endSrcPath;
64
65 1
        return $relativePath;
66
    }
67
}
68