Completed
Push — master ( aa9657...bb9832 )
by Sebastian
05:21
created

Util::isSubDirectoryOf()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.2
cc 4
eloc 5
nc 3
nop 2
crap 4
1
<?php
2
/**
3
 * This file is part of CaptainHook.
4
 *
5
 * (c) Sebastian Feldmann <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace SebastianFeldmann\CaptainHook\Storage;
11
12
/**
13
 * Util class
14
 *
15
 * @package CaptainHook
16
 * @author  Sebastian Feldmann <[email protected]>
17
 * @link    https://github.com/sebastianfeldmann/captainhook
18
 * @since   Class available since Release 1.0.4
19
 */
20
class Util
21
{
22
    /**
23
     * Array representation of a path.
24
     *
25
     * @param  string $path
26
     * @return array
27
     */
28 4
    public static function pathToArray(string $path) : array
29
    {
30 4
        return explode(DIRECTORY_SEPARATOR, ltrim($path, DIRECTORY_SEPARATOR));
31
    }
32
33
    /**
34
     * Is the given subDir a sub directory of given parentDir.
35
     *
36
     * @param  array $subDir
37
     * @param  array $parentDir
38
     * @return bool
39
     */
40 6
    public static function isSubDirectoryOf(array $subDir, array $parentDir) : bool
41
    {
42 6
        foreach ($parentDir as $index => $dir) {
43 6
            if (!isset($subDir[$index]) || $dir !== $subDir[$index]) {
44 6
                return false;
45
            }
46
        }
47 4
        return true;
48
    }
49
50
    /**
51
     * Return the relative path from parentDir to subDir.
52
     *
53
     * @param  array $subDir
54
     * @param  array $parentDir
55
     * @return string
56
     */
57 4
    public static function getSubPathOf(array $subDir, array $parentDir) : string
58
    {
59 4
        if (!self::isSubDirectoryOf($subDir, $parentDir)) {
60 1
            throw new \RuntimeException('Invalid sub directory');
61
        }
62
63 3
        $path = [];
64 3
        foreach (array_slice($subDir, count($parentDir)) as $dir) {
65 3
            $path[] = $dir;
66
        }
67 3
        return implode(DIRECTORY_SEPARATOR, $path);
68
    }
69
}
70