Skip to content

Commit 6bb4e31

Browse files
committed
Consider int range offset in truthy context
1 parent e411d50 commit 6bb4e31

File tree

2 files changed

+9
-18
lines changed

2 files changed

+9
-18
lines changed

src/Analyser/TypeSpecifier.php

+6-15
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ public function specifyTypesInCondition(
280280
$sizeType = IntegerRangeType::createAllGreaterThan($leftType->getValue());
281281
}
282282
} elseif ($leftType instanceof IntegerRangeType) {
283-
$sizeType = $leftType;
283+
$sizeType = $leftType->shift($offset);
284284
}
285285

286286
$specifiedTypes = $this->specifyTypesForCountFuncCall($expr->right, $argType, $sizeType, $context, $scope, $expr);
@@ -1061,23 +1061,14 @@ private function specifyTypesForCountFuncCall(FuncCall $countFuncCall, Type $typ
10611061

10621062
$arraySize = $type->getArraySize();
10631063
$isSize = $sizeType->isSuperTypeOf($arraySize);
1064-
if ($context->truthy()) {
1065-
if ($isSize->no()) {
1066-
return new NeverType();
1067-
}
1068-
1069-
$constArray = $this->turnListIntoConstantArray($type, $sizeType);
1070-
if ($constArray !== null) {
1071-
$type = $constArray;
1072-
}
1064+
if ($context->truthy() && $isSize->no()) {
1065+
return new NeverType();
10731066
}
1074-
if ($context->falsey()) {
1075-
if (!$isSize->yes()) {
1076-
return new NeverType();
1077-
}
1067+
if ($context->falsey() && !$isSize->yes()) {
1068+
return new NeverType();
10781069
}
10791070

1080-
return $type;
1071+
return $this->turnListIntoConstantArray($type, $sizeType) ?? $type;
10811072
});
10821073

10831074
return $this->create($countFuncCall->getArgs()[0]->value, $resultType, $context, $scope)->setRootExpr($rootExpr);

tests/PHPStan/Analyser/nsrt/bug-4700.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ function(array $array, int $count): void {
4141
if (isset($array['e'])) $a[] = $array['e'];
4242
if (count($a) > $count) {
4343
assertType('int<2, 5>', count($a));
44-
assertType('array{0: mixed~null, 1?: mixed~null, 2?: mixed~null, 3?: mixed~null, 4?: mixed~null}', $a);
44+
assertType('list{0: mixed~null, 1: mixed~null, 2?: mixed~null, 3?: mixed~null, 4?: mixed~null}', $a);
4545
} else {
46-
assertType('0', count($a));
47-
assertType('array{}', $a);
46+
assertType('int<0, 5>', count($a)); // Could be int<0, 1>
47+
assertType('array{}|array{0: mixed~null, 1?: mixed~null, 2?: mixed~null, 3?: mixed~null, 4?: mixed~null}', $a); // Could be array{}|array{0: mixed~null}
4848
}
4949
};

0 commit comments

Comments
 (0)