Repository navigation
Expand file tree
/
Copy pathPHPRegexReader.php
More file actions
64 lines (53 loc) · 1.87 KB
/
Copy pathPHPRegexReader.php
File metadata and controls
64 lines (53 loc) · 1.87 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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Regex;
use PHPRegex\Parser\Exception\RegexException;
use PHPRegex\Parser\Node\RegexNode;
use PHPRegex\Parser\PcreTarget;
use PHPRegex\Parser\RegexParser;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Php\PcreVersion;
use PHPStan\Php\PhpVersion;
/**
* Reads a pattern body into the PHPRegex AST, judged for the analysed
* project: the analysed PHP and its bundled engine, narrowed below it when
* the config or composer.json names an older one — a pin never raises the
* judged engine above what that PHP can run. A padded \x{ 41 } escape is
* the letter A on the engines PHP 8.x ships with and the letter x then
* text on PHP 7.4's, and the trees follow that verdict.
*/
#[AutowiredService]
final class PHPRegexReader
{
private ?RegexParser $parser = null;
public function __construct(
private PhpVersion $phpVersion,
private PcreVersion $pcreVersion,
)
{
}
/**
* @param string $rawRegex the pattern body, delimiters and modifiers stripped
* @param string $modifiers the pattern modifiers as RegexGroupParser read them
* @param string $delimiter the opening delimiter of the pattern as written
*
* @throws RegexException when the pattern body cannot be read
*/
public function read(string $rawRegex, string $modifiers, string $delimiter): RegexNode
{
$this->parser ??= RegexParser::create($this->targetOptions());
return $this->parser->parsePattern($rawRegex, $modifiers, $delimiter);
}
/**
* @return array<string, int|string>
*/
private function targetOptions(): array
{
$phpVersionId = $this->phpVersion->getVersionId();
$bundled = PcreTarget::bundledWith($phpVersionId);
$options = ['php_version' => $phpVersionId];
if (!$this->pcreVersion->atLeast($bundled->pcreVersion)) {
$options['pcre_version'] = $this->pcreVersion->getVersionString();
}
return $options;
}
}