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