1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Webrouse\AssetMacro; |
4
|
|
|
|
5
|
|
|
use Webrouse\AssetMacro\Exceptions\InvalidPathException; |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
class Utils |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @param string $path |
13
|
|
|
* @param string $separator |
14
|
|
|
* @return string |
15
|
|
|
*/ |
16
|
1 |
|
public static function normalizePath($path, $separator = '\\/') |
17
|
|
|
{ |
18
|
|
|
// Remove any kind of unicode whitespace |
19
|
1 |
|
$normalized = preg_replace('#\p{C}+|^\./#u', '', $path); |
20
|
|
|
|
21
|
|
|
// Path remove self referring paths ("/./"). |
22
|
1 |
|
$normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized); |
23
|
|
|
|
24
|
|
|
// Regex for resolving relative paths |
25
|
1 |
|
$regex = '#\/*[^/\.]+/\.\.#Uu'; |
26
|
|
|
|
27
|
1 |
|
while (preg_match($regex, $normalized)) { |
28
|
|
|
$normalized = preg_replace($regex, '', $normalized); |
29
|
|
|
} |
30
|
|
|
|
31
|
1 |
|
if (preg_match('#/\.{2}|\.{2}/#', $normalized)) { |
32
|
|
|
throw new InvalidPathException( |
33
|
|
|
sprintf("Path is outside of the defined root, path: '%s', resolved: '%s'.", $path, $normalized) |
34
|
|
|
); |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
return rtrim($normalized, $separator); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Throw exception, trigger error or ignore according of action |
43
|
|
|
* @param \Exception $e |
44
|
|
|
* @param string $action |
45
|
|
|
* @param bool $need |
46
|
|
|
* @throws \Exception |
47
|
|
|
*/ |
48
|
1 |
|
public static function throwError(\Exception $e, $action = 'exception', $need = TRUE) |
49
|
|
|
{ |
50
|
1 |
|
if ($need) { |
51
|
1 |
|
if ($action === 'exception') { |
52
|
1 |
|
throw $e; |
53
|
|
|
|
54
|
1 |
|
} elseif ($action === 'notice') { |
55
|
1 |
|
trigger_error($e->getMessage(), E_USER_NOTICE); |
56
|
|
|
} |
57
|
|
|
} |
58
|
1 |
|
} |
59
|
|
|
|
60
|
|
|
} |
61
|
|
|
|