Skip to content

Commit 008f65e

Browse files
authored
RegexArrayShapeMatcher - Don't optimize alternations with optional groups for tagged unions
1 parent f7b6fe3 commit 008f65e

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

src/Type/Php/RegexArrayShapeMatcher.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,10 @@ private function getOnlyTopLevelAlternation(array $captureGroups): ?RegexAlterna
280280
return null;
281281
}
282282

283+
if ($captureGroup->inOptionalQuantification()) {
284+
return null;
285+
}
286+
283287
if ($alternation === null) {
284288
$alternation = $captureGroup->getAlternation();
285289
} elseif ($alternation->getId() !== $captureGroup->getAlternation()->getId()) {

src/Type/Regex/RegexCapturingGroup.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ public function isOptional(): bool
8282
|| $this->parent !== null && $this->parent->isOptional();
8383
}
8484

85+
public function inOptionalQuantification(): bool
86+
{
87+
return $this->inOptionalQuantification;
88+
}
89+
8590
public function inOptionalAlternation(): bool
8691
{
8792
if (!$this->inAlternation()) {

tests/PHPStan/Analyser/nsrt/preg_match_shapes.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,3 +753,18 @@ function bug11622 (string $expression): void {
753753
assertType("array{string, string}", $matches);
754754
}
755755
}
756+
757+
function bug11604 (string $string): void {
758+
if (! preg_match('/(XX)|(YY)?ZZ/', $string, $matches)) {
759+
return;
760+
}
761+
762+
assertType("array{0: string, 1?: ''|'XX', 2?: 'YY'}", $matches);
763+
// could be array{string, '', 'YY'}|array{string, 'XX'}|array{string}
764+
}
765+
766+
function bug11604b (string $string): void {
767+
if (preg_match('/(XX)|(YY)?(ZZ)/', $string, $matches)) {
768+
assertType("array{0: string, 1?: ''|'XX', 2?: ''|'YY', 3?: 'ZZ'}", $matches);
769+
}
770+
}

0 commit comments

Comments
 (0)