Skip to content

Commit 37a1e86

Browse files
committed
update AST with empty tokens for alternations
1 parent 5533d9f commit 37a1e86

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

src/Type/Regex/RegexGroupParser.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use PHPStan\Type\StringType;
2121
use PHPStan\Type\Type;
2222
use PHPStan\Type\TypeCombinator;
23+
use function array_values;
2324
use function count;
2425
use function in_array;
2526
use function is_int;
@@ -78,6 +79,8 @@ public function parseGroups(string $regex): ?array
7879
}
7980
}
8081

82+
$this->updateAlternationAstRemoveVerticalBarsAndAddEmptyToken($ast);
83+
8184
$captureOnlyNamed = false;
8285
if ($this->phpVersion->supportsPregCaptureOnlyNamedGroups()) {
8386
$captureOnlyNamed = str_contains($modifiers, 'n');
@@ -98,6 +101,31 @@ public function parseGroups(string $regex): ?array
98101
return [$astWalkResult->getCapturingGroups(), $astWalkResult->getMarkVerbs()];
99102
}
100103

104+
private function updateAlternationAstRemoveVerticalBarsAndAddEmptyToken(TreeNode $ast): void
105+
{
106+
$children = $ast->getChildren();
107+
108+
foreach ($children as $i => $child) {
109+
$this->updateAlternationAstRemoveVerticalBarsAndAddEmptyToken($child);
110+
111+
if ($ast->getId() !== '#alternation' || $child->getValueToken() !== 'alternation') {
112+
continue;
113+
}
114+
115+
unset($children[$i]);
116+
117+
if ($i !== 0
118+
&& isset($children[$i + 1])
119+
&& $children[$i + 1]->getValueToken() !== 'alternation') {
120+
continue;
121+
}
122+
123+
$children[$i] = new TreeNode('token', ['token' => 'literal', 'value' => '', 'namespace' => 'default'], [], $ast);
124+
}
125+
126+
$ast->setChildren(array_values($children));
127+
}
128+
101129
private function walkRegexAst(
102130
TreeNode $ast,
103131
?RegexAlternation $alternation,

tests/PHPStan/Command/IgnoredRegexValidatorTest.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,15 @@ public function dataValidate(): array
104104
'~Result of || is always true.~',
105105
[],
106106
false,
107-
true,
107+
false,
108108
],
109109
[
110110
'#Method PragmaRX\Notified\Data\Repositories\Notified::firstOrCreateByEvent() should return PragmaRX\Notified\Data\Models\Notified but returns Illuminate\Database\Eloquent\Model|null#',
111-
[],
111+
[
112+
'null' => 'null',
113+
],
114+
false,
112115
false,
113-
true,
114116
],
115117
];
116118
}

0 commit comments

Comments
 (0)