-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathRegexChecker.php
118 lines (96 loc) · 2.7 KB
/
RegexChecker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
declare(strict_types=1);
/*
* This file is part of the humbug/php-scoper package.
*
* Copyright (c) 2017 Théo FIDRY <theo.fidry@gmail.com>,
* Pádraic Brady <padraic.brady@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Humbug\PhpScoper\Configuration;
use function array_pop;
use function count;
use function explode;
use function in_array;
use function preg_last_error;
use function preg_last_error_msg;
use function preg_match as native_preg_match;
use function sprintf;
use function str_split;
use function strlen;
final class RegexChecker
{
// Some characters are best to not be allowed as regex delimiters in order
// to not result in some fancy regexes
// See https://github.com/humbug/php-scoper/issues/597
private const INVALID_REGEX_DELIMITERS = [
'\\',
'_',
];
// https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
private const PATTERN_MODIFIERS = [
'i',
'm',
's',
'x',
'A',
'D',
'S',
'U',
'X',
'J',
'u',
];
public function isRegexLike(string $value): bool
{
$valueLength = strlen($value);
if ($valueLength < 2) {
return false;
}
/** @var non-empty-string $firstCharacter */
$firstCharacter = $value[0];
if (!self::isValidDelimiter($firstCharacter)) {
return false;
}
$parts = explode($firstCharacter, $value);
if (count($parts) !== 3) {
return false;
}
$lastPart = array_pop($parts);
if (!self::isValidRegexFlags($lastPart)) {
return false;
}
return true;
}
public function validateRegex(string $regex): ?string
{
if (@native_preg_match($regex, '') !== false) {
return null;
}
return sprintf(
'Invalid regex: %s (code %s)',
preg_last_error_msg(),
preg_last_error(),
);
}
private static function isValidDelimiter(string $delimiter): bool
{
return !in_array($delimiter, self::INVALID_REGEX_DELIMITERS, true)
&& native_preg_match('/^\p{L}$/u', $delimiter) === 0;
}
private static function isValidRegexFlags(string $value): bool
{
if ('' === $value) {
return true;
}
$characters = str_split($value);
foreach ($characters as $character) {
if (!in_array($character, self::PATTERN_MODIFIERS, true)) {
return false;
}
}
return true;
}
}