Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 21 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,27 @@ private function specifyTypesForCountFuncCall(
return $result;
}
}

// Fallback: directly filter constant arrays by their exact sizes.
// This avoids using TypeCombinator::remove() with falsey context,
// which can incorrectly remove arrays whose count doesn't match
// but whose shape is a subtype of the matched array.
$keptTypes = [];
foreach ($type->getConstantArrays() as $arrayType) {
if ($sizeType->isSuperTypeOf($arrayType->getArraySize())->yes()) {
continue;
}

$keptTypes[] = $arrayType;
}
if ($keptTypes !== []) {
return $this->create(
$countFuncCall->getArgs()[0]->value,
TypeCombinator::union(...$keptTypes),
$context->negate(),
$scope,
)->setRootExpr($rootExpr);
}
}

$resultTypes = [];
Expand Down
20 changes: 20 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-14314.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types = 1);

namespace Bug14314;

use function PHPStan\Testing\assertType;

function () {
preg_match('/^(.)$/', '', $matches) || preg_match('/^(.)(.)(.)$/', '', $matches);
assertType('array{}|array{non-falsy-string, non-empty-string, non-empty-string, non-empty-string}|array{non-falsy-string, non-empty-string}', $matches);
if (count($matches) === 2) {
assertType('array{non-falsy-string, non-empty-string}', $matches);
return;
}
assertType('array{}|array{non-falsy-string, non-empty-string, non-empty-string, non-empty-string}', $matches);
if (count($matches) === 4) {
assertType('array{non-falsy-string, non-empty-string, non-empty-string, non-empty-string}', $matches);
}
};
Loading