Skip to content
Open
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
18 changes: 7 additions & 11 deletions src/Type/Php/ArrayCountValuesDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\NeverType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
Expand Down Expand Up @@ -43,22 +45,16 @@ public function getTypeFromFunctionCall(
$arrayTypes = $inputType->getArrays();

$outputTypes = [];
$allowedValues = new UnionType([new IntegerType(), new StringType()]);

foreach ($arrayTypes as $arrayType) {
$itemType = $arrayType->getItemType();

if ($itemType instanceof UnionType) {
$itemType = $itemType->filterTypes(
static fn ($type) => !$type->toArrayKey() instanceof ErrorType,
);
}

if ($itemType->toArrayKey() instanceof ErrorType) {
$itemType = TypeCombinator::intersect($arrayType->getItemType(), $allowedValues);
if ($itemType instanceof NeverType) {
continue;
}

$outputTypes[] = TypeCombinator::intersect(
new ArrayType($itemType, IntegerRangeType::fromInterval(1, null)),
new ArrayType($itemType->toArrayKey(), IntegerRangeType::fromInterval(1, null)),
new NonEmptyArrayType(),
);
}
Expand Down
9 changes: 9 additions & 0 deletions tests/PHPStan/Analyser/nsrt/array-count-values.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,12 @@ public function __toString(): string
$stringable = array_count_values([new StringableObject(), 'string', 1]);

assertType('non-empty-array<1|\'string\', int<1, max>>', $stringable);

// Booleans, floats and null are ignored by array_count_values even if they can be cast to array key.
$scalar = array_count_values([true, 1.0, false, 0.0, null]);

assertType('array{}', $scalar);

$intAsString = array_count_values(['1', '2', '2', '3']);

assertType("non-empty-array<1|2|3, int<1, max>>", $intAsString);
Loading