Skip to content

Commit ca7703e

Browse files
committed
RegexArrayShapeMatcher - optional non-last groups can be empty-string
1 parent b7fe990 commit ca7703e

File tree

2 files changed

+5
-4
lines changed

2 files changed

+5
-4
lines changed

src/Type/Php/RegexArrayShapeMatcher.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,8 @@ private function buildArrayType(
297297
$i = 0;
298298
foreach ($captureGroups as $captureGroup) {
299299
$isTrailingOptional = $i >= $countGroups - $trailingOptionals;
300-
$groupValueType = $this->createGroupValueType($captureGroup, $wasMatched, $flags, $isTrailingOptional, $matchesAll);
300+
$isLastGroup = $i === $countGroups - 1;
301+
$groupValueType = $this->createGroupValueType($captureGroup, $wasMatched, $flags, $isTrailingOptional, $isLastGroup, $matchesAll);
301302
$optional = $this->isGroupOptional($captureGroup, $wasMatched, $flags, $isTrailingOptional, $matchesAll);
302303

303304
if ($captureGroup->isNamed()) {
@@ -390,7 +391,7 @@ private function isGroupOptional(RegexCapturingGroup $captureGroup, TrinaryLogic
390391
return $optional;
391392
}
392393

393-
private function createGroupValueType(RegexCapturingGroup $captureGroup, TrinaryLogic $wasMatched, int $flags, bool $isTrailingOptional, bool $matchesAll): Type
394+
private function createGroupValueType(RegexCapturingGroup $captureGroup, TrinaryLogic $wasMatched, int $flags, bool $isTrailingOptional, bool $isLastGroup, bool $matchesAll): Type
394395
{
395396
$groupValueType = $this->getValueType($captureGroup->getType(), $flags, $matchesAll);
396397

@@ -417,7 +418,7 @@ private function createGroupValueType(RegexCapturingGroup $captureGroup, Trinary
417418
}
418419
}
419420

420-
if (!$isTrailingOptional && !$this->containsUnmatchedAsNull($flags, $matchesAll) && $captureGroup->isOptional()) {
421+
if (!$isLastGroup && !$this->containsUnmatchedAsNull($flags, $matchesAll) && $captureGroup->isOptional()) {
421422
$groupValueType = TypeCombinator::union($groupValueType, new ConstantStringType(''));
422423
}
423424

tests/PHPStan/Analyser/nsrt/preg_match_shapes.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -567,7 +567,7 @@ function (string $s): void {
567567
}
568568

569569
if (preg_match($p, $s, $matches)) {
570-
assertType("array{0: string, 1: non-empty-string, 2?: numeric-string, 3?: 'x'}", $matches);
570+
assertType("array{0: string, 1: non-empty-string, 2?: ''|numeric-string, 3?: 'x'}", $matches);
571571
}
572572
};
573573

0 commit comments

Comments
 (0)