1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Humbug\PhpScoper\Configuration; |
6
|
|
|
|
7
|
|
|
use function array_pop; |
8
|
|
|
use function count; |
9
|
|
|
use function explode; |
10
|
|
|
use function in_array; |
11
|
|
|
use function preg_last_error; |
12
|
|
|
use function preg_last_error_msg; |
13
|
|
|
use function preg_match as native_preg_match; |
14
|
|
|
use function Safe\sprintf; |
15
|
|
|
use function str_split; |
16
|
|
|
use function strlen; |
17
|
|
|
|
18
|
|
|
final class RegexChecker |
19
|
|
|
{ |
20
|
|
|
// https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php |
21
|
|
|
private const PATTERN_MODIFIERS = [ |
22
|
|
|
'i', |
23
|
|
|
'm', |
24
|
|
|
's', |
25
|
|
|
'x', |
26
|
|
|
'A', |
27
|
|
|
'D', |
28
|
|
|
'S', |
29
|
|
|
'U', |
30
|
|
|
'X', |
31
|
|
|
'J', |
32
|
|
|
'u', |
33
|
|
|
]; |
34
|
|
|
|
35
|
|
|
public function isRegexLike(string $value): bool |
36
|
|
|
{ |
37
|
|
|
$valueLength = strlen($value); |
38
|
|
|
|
39
|
|
|
if ($valueLength < 2) { |
40
|
|
|
return false; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$firstCharacter = $value[0]; |
44
|
|
|
|
45
|
|
|
if (!self::isValidDelimiter($firstCharacter)) { |
46
|
|
|
return false; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$parts = explode($firstCharacter, $value); |
50
|
|
|
|
51
|
|
|
if (false === $parts || count($parts) !== 3) { |
52
|
|
|
return false; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$lastPart = array_pop($parts); |
56
|
|
|
|
57
|
|
|
if (!self::isValidRegexFlags($lastPart)) { |
58
|
|
|
return false; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return true; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function validateRegex(string $regex): ?string |
65
|
|
|
{ |
66
|
|
|
if (@native_preg_match($regex, '') !== false) { |
67
|
|
|
return null; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return sprintf( |
71
|
|
|
'Invalid regex: %s (code %s)', |
72
|
|
|
preg_last_error_msg(), |
73
|
|
|
preg_last_error(), |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
private static function isValidDelimiter(string $delimiter): bool |
78
|
|
|
{ |
79
|
|
|
// This is not ideal as not true but is good enough for our case. |
80
|
|
|
// See https://github.com/humbug/php-scoper/issues/597 |
81
|
|
|
return '\\' !== $delimiter && native_preg_match('/^\p{L}$/u', $delimiter) === 0; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
private static function isValidRegexFlags(string $value): bool |
85
|
|
|
{ |
86
|
|
|
if ('' === $value) { |
87
|
|
|
return true; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$characters = str_split($value); |
91
|
|
|
|
92
|
|
|
foreach ($characters as $character) { |
93
|
|
|
if (!in_array($character, self::PATTERN_MODIFIERS, true)) { |
94
|
|
|
return false; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return true; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|