Skip to content

Commit

Permalink
RegexArrayShapeMatcher: Fix non-emptiness of leading optional groups
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored Jul 25, 2024
1 parent c4c0269 commit 4d055b0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Type/Php/RegexArrayShapeMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -286,12 +286,13 @@ private function buildArrayType(
$countGroups = count($captureGroups);
$i = 0;
foreach ($captureGroups as $captureGroup) {
$isTrailingOptional = $i >= $countGroups - $trailingOptionals;
$groupValueType = $this->getValueType($captureGroup->getType(), $flags);

if (!$wasMatched->yes()) {
$optional = true;
} else {
if ($i < $countGroups - $trailingOptionals) {
if (!$isTrailingOptional) {
$optional = false;
if ($this->containsUnmatchedAsNull($flags) && !$captureGroup->isOptional()) {
$groupValueType = TypeCombinator::removeNull($groupValueType);
Expand All @@ -303,7 +304,7 @@ private function buildArrayType(
}
}

if (!$optional && $captureGroup->isOptional() && !$this->containsUnmatchedAsNull($flags)) {
if (!$isTrailingOptional && $captureGroup->isOptional() && !$this->containsUnmatchedAsNull($flags)) {
$groupValueType = TypeCombinator::union($groupValueType, new ConstantStringType(''));
}

Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Analyser/nsrt/preg_match_shapes.php
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,18 @@ function (string $s): void {
assertType("array{0?: string, 1?: ''|numeric-string}", $matches);
};

class Bug11376
{
public function test(string $str): void
{
preg_match('~^(?:(\w+)::)?(\w+)$~', $str, $matches);
assertType('array{0?: string, 1?: string, 2?: non-empty-string}', $matches);
}

public function test2(string $str): void
{
if (preg_match('~^(?:(\w+)::)?(\w+)$~', $str, $matches) === 1) {
assertType('array{string, string, non-empty-string}', $matches);
}
}
}

0 comments on commit 4d055b0

Please sign in to comment.