Skip to content

RegexArrayShapeMatcher - Fix PREG_UNMATCHED_AS_NULL with top level alternation #3238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Type/Php/RegexArrayShapeMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched
$beforeCurrentCombo = false;
} elseif ($beforeCurrentCombo && !$group->resetsGroupCounter()) {
$group->forceNonOptional();
} elseif ($group->getAlternationId() === $onlyTopLevelAlternationId) {
} elseif ($group->getAlternationId() === $onlyTopLevelAlternationId && !$this->containsUnmatchedAsNull($flags ?? 0)) {
unset($comboList[$groupId]);
}
}
Expand All @@ -191,7 +191,7 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched
}
}

if ($isOptionalAlternation) {
if ($isOptionalAlternation && !$this->containsUnmatchedAsNull($flags ?? 0)) {
$combiTypes[] = new ConstantArrayType([new ConstantIntegerType(0)], [new StringType()], [0], [], true);
}

Expand Down
14 changes: 14 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-11311.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,17 @@ function bug11331c(string $url):void {
assertType('array{string, string|null, string|null, string, string}', $matches);
}
}

class UnmatchedAsNullWithTopLevelAlternation {
function doFoo(string $s): void {
if (preg_match('/Price: (?:(£)|(€))\d+/', $s, $matches, PREG_UNMATCHED_AS_NULL)) {
assertType('array{string, string|null, string|null}', $matches); // could be array{0: string, 1: null, 2: string}|array{0: string, 1: string, 2: null}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that would be nicer for sure ;) But strictly speaking at least this is correct.

}
}

function doBar(string $s): void {
if (preg_match('/Price: (?:(£)|(€))?\d+/', $s, $matches, PREG_UNMATCHED_AS_NULL)) {
assertType('array{string, string|null, string|null}', $matches);
}
}
}
Loading