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