Skip to content

Commit

Permalink
Fix count() narrowing on $matches
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Jul 3, 2024
1 parent 0b3e74f commit 74d58e4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Type/Php/RegexArrayShapeMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched
);

return TypeCombinator::union(
new ConstantArrayType([new ConstantIntegerType(0)], [new StringType()]),
new ConstantArrayType([new ConstantIntegerType(0)], [new StringType()], [0], [], true),
$combiType,
);
} elseif (
Expand Down Expand Up @@ -156,7 +156,7 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched
}

if ($isOptionalAlternation) {
$combiTypes[] = new ConstantArrayType([new ConstantIntegerType(0)], [new StringType()]);
$combiTypes[] = new ConstantArrayType([new ConstantIntegerType(0)], [new StringType()], [0], [], true);
}

return TypeCombinator::union(...$combiTypes);
Expand Down
23 changes: 23 additions & 0 deletions tests/PHPStan/Analyser/nsrt/preg_match_shapes.php
Original file line number Diff line number Diff line change
Expand Up @@ -337,3 +337,26 @@ function (string $size): void {
assertType('array{0: string, 1: string, 2?: string, 3?: string}', $matches);
};


function bug11277a(string $value): void
{
if (preg_match('/^\[(.+,?)*\]$/', $value, $matches)) {
assertType('array{0: string, 1?: string}', $matches);
if (count($matches) === 2) {
assertType('array{string, string}', $matches);
}
}
}

function bug11277b(string $value): void
{
if (preg_match('/^(?:(.+,?)|(x))*$/', $value, $matches)) {
assertType('array{0: string, 1?: string, 2?: string}', $matches);
if (count($matches) === 2) {
assertType('array{string, string}', $matches);
}
if (count($matches) === 3) {
assertType('array{string, string, string}', $matches);
}
}
}

0 comments on commit 74d58e4

Please sign in to comment.