|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace AppUtils\FileHelper; |
|
6
|
|
|
|
|
7
|
|
|
use AppUtils\FileHelper; |
|
8
|
|
|
|
|
9
|
|
|
class PathRelativizer |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Makes a path relative using a folder depth: will reduce the |
|
13
|
|
|
* length of the path so that only the amount of folders defined |
|
14
|
|
|
* in the <code>$depth</code> attribute are shown below the actual |
|
15
|
|
|
* folder or file in the path. |
|
16
|
|
|
* |
|
17
|
|
|
* @param string $path The absolute or relative path |
|
18
|
|
|
* @param int $depth The folder depth to reduce the path to |
|
19
|
|
|
* @return string |
|
20
|
|
|
*/ |
|
21
|
|
|
public static function relativizeByDepth(string $path, int $depth=2) : string |
|
22
|
|
|
{ |
|
23
|
|
|
$path = FileHelper::normalizePath($path); |
|
24
|
|
|
|
|
25
|
|
|
$tokens = explode('/', $path); |
|
26
|
|
|
$tokens = array_filter($tokens); // remove empty entries (trailing slash for example) |
|
27
|
|
|
$tokens = array_values($tokens); // re-index keys |
|
28
|
|
|
|
|
29
|
|
|
if(empty($tokens)) { |
|
30
|
|
|
return ''; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
// remove the drive if present |
|
34
|
|
|
if(strpos($tokens[0], ':') !== false) { |
|
35
|
|
|
array_shift($tokens); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
// path was only the drive |
|
39
|
|
|
if(count($tokens) === 0) { |
|
40
|
|
|
return ''; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
// the last element (file or folder) |
|
44
|
|
|
$target = array_pop($tokens); |
|
45
|
|
|
|
|
46
|
|
|
// reduce the path to the specified depth |
|
47
|
|
|
$length = count($tokens); |
|
48
|
|
|
if($length > $depth) { |
|
49
|
|
|
$tokens = array_slice($tokens, $length-$depth); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
// append the last element again |
|
53
|
|
|
$tokens[] = $target; |
|
54
|
|
|
|
|
55
|
|
|
return trim(implode('/', $tokens), '/'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Makes the specified path relative to another path, |
|
60
|
|
|
* by removing one from the other if found. Also |
|
61
|
|
|
* normalizes the path to use forward slashes. |
|
62
|
|
|
* |
|
63
|
|
|
* Example: |
|
64
|
|
|
* |
|
65
|
|
|
* <pre> |
|
66
|
|
|
* relativizePath('c:\some\folder\to\file.txt', 'c:\some\folder'); |
|
67
|
|
|
* </pre> |
|
68
|
|
|
* |
|
69
|
|
|
* Result: <code>to/file.txt</code> |
|
70
|
|
|
* |
|
71
|
|
|
* @param string $path |
|
72
|
|
|
* @param string $relativeTo |
|
73
|
|
|
* @return string |
|
74
|
|
|
*/ |
|
75
|
|
|
public static function relativize(string $path, string $relativeTo) : string |
|
76
|
|
|
{ |
|
77
|
|
|
$path = FileHelper::normalizePath($path); |
|
78
|
|
|
$relativeTo = FileHelper::normalizePath($relativeTo); |
|
79
|
|
|
|
|
80
|
|
|
$relative = str_replace($relativeTo, '', $path); |
|
81
|
|
|
|
|
82
|
|
|
return trim($relative, '/'); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|