Skip to content

Commit bc25fa3

Browse files
committed
update AST with empty tokens for alternations
1 parent b0f1dcb commit bc25fa3

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;
@@ -67,6 +68,8 @@ public function parseGroups(string $regex): ?array
6768
return null;
6869
}
6970

71+
$this->updateAlternationAstRemoveVerticalBarsAndAddEmptyToken($ast);
72+
7073
$captureOnlyNamed = false;
7174
$modifiers = $this->regexExpressionHelper->getPatternModifiers($regex) ?? '';
7275
if ($this->phpVersion->supportsPregCaptureOnlyNamedGroups()) {
@@ -88,6 +91,31 @@ public function parseGroups(string $regex): ?array
8891
return [$astWalkResult->getCapturingGroups(), $astWalkResult->getMarkVerbs()];
8992
}
9093

94+
private function updateAlternationAstRemoveVerticalBarsAndAddEmptyToken(TreeNode $ast): void
95+
{
96+
$children = $ast->getChildren();
97+
98+
foreach ($children as $i => $child) {
99+
$this->updateAlternationAstRemoveVerticalBarsAndAddEmptyToken($child);
100+
101+
if ($ast->getId() !== '#alternation' || $child->getValueToken() !== 'alternation') {
102+
continue;
103+
}
104+
105+
unset($children[$i]);
106+
107+
if ($i !== 0
108+
&& isset($children[$i + 1])
109+
&& $children[$i + 1]->getValueToken() !== 'alternation') {
110+
continue;
111+
}
112+
113+
$children[$i] = new TreeNode('token', ['token' => 'literal', 'value' => '', 'namespace' => 'default'], [], $ast);
114+
}
115+
116+
$ast->setChildren(array_values($children));
117+
}
118+
91119
private function walkRegexAst(
92120
TreeNode $ast,
93121
?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)