Skip to content
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
39 changes: 39 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -1403,6 +1403,45 @@ private function specifyTypesForCountFuncCall(
$resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
}

if ($context->truthy() && $isConstantArray->yes() && $isList->yes()) {
$hasOptionalKeys = false;
foreach ($type->getConstantArrays() as $arrayType) {
if ($arrayType->getOptionalKeys() !== []) {
$hasOptionalKeys = true;
break;
}
}

if (!$hasOptionalKeys) {
$argExpr = $countFuncCall->getArgs()[0]->value;
$argExprString = $this->exprPrinter->printExpr($argExpr);

$sizeMin = null;
$sizeMax = null;
if ($sizeType instanceof ConstantIntegerType) {
$sizeMin = $sizeType->getValue();
$sizeMax = $sizeType->getValue();
} elseif ($sizeType instanceof IntegerRangeType) {
$sizeMin = $sizeType->getMin();
$sizeMax = $sizeType->getMax();
}

$sureTypes = [];
$sureNotTypes = [];

if ($sizeMin !== null && $sizeMin >= 1) {
$sureTypes[$argExprString] = [$argExpr, new HasOffsetValueType(new ConstantIntegerType($sizeMin - 1), new MixedType())];
}
if ($sizeMax !== null) {
$sureNotTypes[$argExprString] = [$argExpr, new HasOffsetValueType(new ConstantIntegerType($sizeMax), new MixedType())];
}

if ($sureTypes !== [] || $sureNotTypes !== []) {
return (new SpecifiedTypes($sureTypes, $sureNotTypes))->setRootExpr($rootExpr);
}
}
}

return $this->create($countFuncCall->getArgs()[0]->value, TypeCombinator::union(...$resultTypes), $context, $scope)->setRootExpr($rootExpr);
}

Expand Down
50 changes: 50 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-14301.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php declare(strict_types = 1);

namespace Bug14301;

use function PHPStan\Testing\assertType;

class Foo
{
/**
* @param array{bool}|array{mixed, string|null, mixed} $row
*/
protected function testNotEquals(array $row): string
{
if (count($row) !== 1) {
assertType('array{mixed, string|null, mixed}', $row);

[$field, $operator, $value] = $row;
assertType('string|null', $operator);
return $operator ?? '=';
} else {
assertType('array{bool}', $row);
}

return '';
}

/**
* @param array{bool}|array{mixed, string|null, mixed} $row
*/
protected function testEquals(array $row): void
{
if (count($row) === 3) {
assertType('array{mixed, string|null, mixed}', $row);
} else {
assertType('array{bool}', $row);
}
}

/**
* @param array{bool}|array{mixed, string|null, mixed} $row
*/
protected function testEquals1(array $row): void
{
if (count($row) === 1) {
assertType('array{bool}', $row);
} else {
assertType('array{mixed, string|null, mixed}', $row);
}
}
}
Loading