Repository navigation
Expand file tree
/
Copy pathParserOptions.php
More file actions
433 lines (375 loc) · 14.1 KB
/
Copy pathParserOptions.php
File metadata and controls
433 lines (375 loc) · 14.1 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<?php
declare(strict_types=1);
/*
* This file is part of the PHPRegex package.
*
* (c) Younes ENNAJI <younes.ennaji.pro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPRegex\Parser;
use PHPRegex\Parser\Cache\ArrayCache;
use PHPRegex\Parser\Cache\CacheInterface;
use PHPRegex\Parser\Cache\FilesystemCache;
use PHPRegex\Parser\Cache\NullCache;
use PHPRegex\Parser\Exception\InvalidRegexOptionException;
use PHPRegex\Parser\Internal\Ascii;
use PHPRegex\Parser\Internal\LibraryPcre;
/**
* Configuration options for Regex parser.
*
* Provides a simple, validated way to configure regex parsing behavior
* including limits, caching, and ReDoS pattern exclusions.
*
* The keys are closed and each value has its type; the ranges (a positive
* length, a version that names a release) are checked when the options are
* read, where an InvalidRegexOptionException says which one is wrong.
*
* @phpstan-type OptionsArray array{
* max_pattern_length?: int,
* max_lookbehind_length?: int,
* cache?: CacheInterface|string|null,
* redos_ignored_patterns?: array<string>,
* runtime_pcre_validation?: bool,
* max_recursion_depth?: int,
* php_version?: int|string|null,
* pcre_version?: string|null,
* }
*/
final class ParserOptions
{
/**
* Allowed option keys for configuration.
*/
private const VALID_OPTIONS = [
'max_pattern_length',
'max_lookbehind_length',
'cache',
'redos_ignored_patterns',
'runtime_pcre_validation',
'max_recursion_depth',
'php_version',
'pcre_version',
];
/**
* The PHP version and the PCRE2 release patterns are judged for.
*/
public readonly PcreTarget $target;
/**
* Create new configuration options.
*
* @param int $maxPatternLength Maximum allowed regex pattern length
* @param int $maxLookbehindLength Maximum length of a variable-length lookbehind; a
* fixed-length one is only limited by PCRE's 65535
* @param CacheInterface $cache Cache implementation to use
* @param array<string> $redosIgnoredPatterns Patterns to ignore in ReDoS analysis
* @param bool $runtimePcreValidation Whether to validate against the PCRE runtime
* @param int $maxRecursionDepth Maximum recursion depth during parsing
* @param PcreTarget|null $target The PHP and PCRE2 judged; the running ones when null
*/
public function __construct(
public readonly int $maxPatternLength,
public readonly int $maxLookbehindLength,
public readonly CacheInterface $cache,
public readonly array $redosIgnoredPatterns = [],
public readonly bool $runtimePcreValidation = false,
public readonly int $maxRecursionDepth = RegexParser::DEFAULT_MAX_RECURSION_DEPTH,
?PcreTarget $target = null,
) {
$this->target = $target ?? PcreTarget::runtime();
// PHP compiles with the engine that runs: it judges the target only
// when the target is that engine.
if ($this->runtimePcreValidation && !$this->target->isRunningEngine()) {
throw new InvalidRegexOptionException(\sprintf(
'"runtime_pcre_validation" compiles with the running PHP, which does not judge the target (PHP %d.%d, PCRE2 %s); drop one of them.',
intdiv($this->target->phpVersionId, 10000),
intdiv($this->target->phpVersionId, 100) % 100,
$this->target->pcreVersion,
));
}
}
/**
* Create configuration from array of options.
*
* Reads options from anywhere, a configuration file or a command line
* included: each key and value is checked here. Code that writes its
* options as a literal array passes them to Regex::create() or
* RegexParser::create(), whose OptionsArray shape PHPStan checks.
*
* @param array<string, mixed> $options Configuration options
*
* @return self New configuration instance
*/
public static function fromArray(array $options): self
{
if ([] === $options) {
return self::createDefault();
}
self::validateOptionKeys($options);
$maxLength = self::getPatternLength($options);
$lookbehindLength = self::getLookbehindLength($options);
$cache = self::createCache($options);
$patterns = self::getIgnoredPatterns($options);
$runtimeValidation = self::getRuntimePcreValidation($options);
$recursionDepth = self::getRecursionDepth($options);
$target = self::getTarget($options);
return new self($maxLength, $lookbehindLength, $cache, $patterns, $runtimeValidation, $recursionDepth, $target);
}
/**
* Create default configuration with no custom options.
*
* @return self Default configuration instance
*/
private static function createDefault(): self
{
return new self(
RegexParser::DEFAULT_MAX_PATTERN_LENGTH,
RegexParser::DEFAULT_MAX_LOOKBEHIND_LENGTH,
new ArrayCache(),
[],
false,
);
}
/**
* Validate that all provided option keys are supported.
*
* @param array<string, mixed> $options Options to validate
*/
private static function validateOptionKeys(array $options): void
{
$invalidKeys = array_diff(
array_keys($options),
self::VALID_OPTIONS,
);
if ([] !== $invalidKeys) {
throw new InvalidRegexOptionException(\sprintf(
'Unknown option(s): %s. Allowed options are: %s.',
implode(', ', $invalidKeys),
implode(', ', self::VALID_OPTIONS),
));
}
}
/**
* Get maximum pattern length from options.
*
* @param array<string, mixed> $options Configuration options
*
* @return int Maximum pattern length
*/
private static function getPatternLength(array $options): int
{
$length = $options['max_pattern_length'] ?? RegexParser::DEFAULT_MAX_PATTERN_LENGTH;
if (!\is_int($length) || $length <= 0) {
throw new InvalidRegexOptionException(
'"max_pattern_length" must be a positive integer.',
);
}
return $length;
}
/**
* Get maximum lookbehind length from options.
*
* @param array<string, mixed> $options Configuration options
*
* @return int Maximum lookbehind length
*/
private static function getLookbehindLength(array $options): int
{
$length = $options['max_lookbehind_length'] ?? RegexParser::DEFAULT_MAX_LOOKBEHIND_LENGTH;
if (!\is_int($length) || $length < 0) {
throw new InvalidRegexOptionException(
'"max_lookbehind_length" must be a non-negative integer.',
);
}
return $length;
}
/**
* Get runtime PCRE validation flag from options.
*
* @param array<string, mixed> $options Configuration options
*/
private static function getRuntimePcreValidation(array $options): bool
{
$runtimeValidation = $options['runtime_pcre_validation'] ?? false;
if (!\is_bool($runtimeValidation)) {
throw new InvalidRegexOptionException(
'"runtime_pcre_validation" must be a boolean.',
);
}
return $runtimeValidation;
}
/**
* Get recursion depth from options.
*
* @param array<string, mixed> $options Configuration options
*
* @return int Maximum recursion depth
*/
private static function getRecursionDepth(array $options): int
{
$depth = $options['max_recursion_depth'] ?? RegexParser::DEFAULT_MAX_RECURSION_DEPTH;
if (!\is_int($depth) || $depth <= 0) {
throw new InvalidRegexOptionException(
'"max_recursion_depth" must be a positive integer.',
);
}
return $depth;
}
/**
* The PHP and the PCRE2 judged: the running ones by default, a PHP
* version alone with the PCRE2 it bundles, a PCRE2 release alone with
* the running PHP.
*
* @param array<string, mixed> $options Configuration options
*/
private static function getTarget(array $options): PcreTarget
{
$pcreVersion = $options['pcre_version'] ?? null;
if (null !== $pcreVersion && !\is_string($pcreVersion)) {
throw new InvalidRegexOptionException(\sprintf('"pcre_version" must be a PCRE2 release like "10.44", not a %s.', get_debug_type($pcreVersion)));
}
// "runtime", as PHPStan's phpVersion takes it: the running PHP, with
// the PCRE2 it links unless a release is given beside it.
$phpVersion = $options['php_version'] ?? null;
if (\is_string($phpVersion) && 'runtime' === Ascii::lower(trim($phpVersion, " \t\n\r\0\x0B"))) {
return null === $pcreVersion ? PcreTarget::runtime() : new PcreTarget(PcreTarget::runtime()->phpVersionId, $pcreVersion);
}
$phpVersionId = self::getPhpVersionId($options);
return match (true) {
null === $phpVersionId && null === $pcreVersion => PcreTarget::runtime(),
null === $pcreVersion => PcreTarget::bundledWith((int) $phpVersionId),
default => new PcreTarget($phpVersionId ?? PcreTarget::runtime()->phpVersionId, $pcreVersion),
};
}
/**
* Get target PHP version ID from options.
*
* @param array<string, mixed> $options Configuration options
*/
private static function getPhpVersionId(array $options): ?int
{
$version = $options['php_version'] ?? null;
if (null === $version) {
return null;
}
if (\is_int($version)) {
if ($version <= 0) {
throw new InvalidRegexOptionException(
'"php_version" must be a version string like "8.2", a PHP_VERSION_ID integer, or "runtime".',
);
}
return $version;
}
if (\is_string($version)) {
$trimmed = trim($version, " \t\n\r\0\x0B");
if ('' === $trimmed) {
throw new InvalidRegexOptionException(
'"php_version" must be a version string like "8.2", a PHP_VERSION_ID integer, or "runtime".',
);
}
if (Ascii::isDigit($trimmed)) {
$asInt = (int) $trimmed;
if ($asInt < 10000) {
throw new InvalidRegexOptionException(
'"php_version" must be a version string like "8.2", a PHP_VERSION_ID integer, or "runtime".',
);
}
return $asInt;
}
if (LibraryPcre::match('/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/', $trimmed, $matches)) {
$major = (int) $matches[1];
$minor = isset($matches[2]) && \is_string($matches[2]) ? (int) $matches[2] : 0;
$patch = isset($matches[3]) && \is_string($matches[3]) ? (int) $matches[3] : 0;
return ($major * 10000) + ($minor * 100) + $patch;
}
}
throw new InvalidRegexOptionException(
'"php_version" must be a version string like "8.2", a PHP_VERSION_ID integer, or "runtime".',
);
}
/**
* Create cache instance from options.
*
* @param array<string, mixed> $options Configuration options
*
* @return CacheInterface Cache implementation
*/
private static function createCache(array $options): CacheInterface
{
// Nothing goes to disk unless a directory is named.
if (!\array_key_exists('cache', $options)) {
return new ArrayCache();
}
$cacheOption = $options['cache'];
if (null === $cacheOption) {
return new NullCache();
}
if (\is_string($cacheOption)) {
return self::createFilesystemCache($cacheOption);
}
if ($cacheOption instanceof CacheInterface) {
return $cacheOption;
}
throw new InvalidRegexOptionException(
'The "cache" option must be null, a cache path, or a CacheInterface implementation.',
);
}
/**
* Create filesystem cache from path.
*
* @param string $path Cache directory path
*
* @return FilesystemCache Filesystem cache instance
*/
private static function createFilesystemCache(string $path): FilesystemCache
{
$trimmedPath = trim($path, " \t\n\r\0\x0B");
if ('' === $trimmedPath) {
throw new InvalidRegexOptionException(
'The "cache" option cannot be an empty string.',
);
}
return new FilesystemCache($trimmedPath);
}
/**
* Get ignored ReDoS patterns from options.
*
* @param array<string, mixed> $options Configuration options
*
* @return array<string> List of ignored patterns
*/
private static function getIgnoredPatterns(array $options): array
{
$patterns = $options['redos_ignored_patterns'] ?? [];
if (!\is_array($patterns)) {
throw new InvalidRegexOptionException(
'"redos_ignored_patterns" must be a list of strings.',
);
}
if ([] === $patterns) {
return [];
}
self::validatePatternStrings($patterns);
/** @var array<string> $result */
$result = array_values(array_unique($patterns));
return $result;
}
/**
* Validate that all patterns are strings.
*
* @param array<mixed> $patterns Patterns to validate
*
* @phpstan-assert array<string> $patterns
*/
private static function validatePatternStrings(array $patterns): void
{
foreach ($patterns as $pattern) {
if (!\is_string($pattern)) {
throw new InvalidRegexOptionException(
'"redos_ignored_patterns" must contain only strings.',
);
}
}
}
}