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
6 changes: 6 additions & 0 deletions src/Type/Php/ArrayCountValuesDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ public function getTypeFromFunctionCall(
continue;
}

if (!$itemType->isString()->no() && !$itemType->isConstantScalarValue()->yes()) {
$itemType = $allowedValues;
} else {
$itemType = $itemType->toArrayKey();
}

$outputTypes[] = new IntersectionType([
new ArrayType($itemType->toArrayKey(), IntegerRangeType::fromInterval(1, null)),
new NonEmptyArrayType(),
Expand Down
36 changes: 35 additions & 1 deletion tests/PHPStan/Analyser/nsrt/array-count-values.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function returnsStringOrObjectArray(): array
}

// Objects are ignored by array_count_values, with a warning emitted.
assertType('non-empty-array<string, int<1, max>>', array_count_values(returnsStringOrObjectArray()));
assertType('non-empty-array<int|string, int<1, max>>', array_count_values(returnsStringOrObjectArray()));

class StringableObject
{
Expand All @@ -50,3 +50,37 @@ public function __toString(): string
$intAsString = array_count_values(['1', '2', '2', '3']);

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

/**
* @param array<string> $strings
* @param array<int> $ints
* @param array<positive-int> $positives
* @param array<int<10, 30>> $ranges
* @param array<string|int> $stringOrInts
* @param array<string|bool> $stringsOrBool
* @param array<int|"1"> $intOrConstNumericString
* @param array<int|"A"> $intOrConstNonNumericString
*/
function strings(
array $strings,
array $ints,
array $positives,
array $ranges,
array $stringOrInts,
array $stringsOrBool,
array $intOrConstNumericString,
array $intOrConstNonNumericString,
): void
{
// numeric-strings in array-keys are auto-casted to int, see https://3v4l.org/VQoSJQ#vnull
assertType("non-empty-array<int|string, int<1, max>>", array_count_values($strings));

assertType("non-empty-array<int, int<1, max>>", array_count_values($ints));
assertType("non-empty-array<int<1, max>, int<1, max>>", array_count_values($positives));
assertType("non-empty-array<int<10, 30>, int<1, max>>", array_count_values($ranges));

assertType("non-empty-array<int|string, int<1, max>>", array_count_values($stringOrInts));
assertType("non-empty-array<int|string, int<1, max>>", array_count_values($stringsOrBool));
assertType("non-empty-array<int|string, int<1, max>>", array_count_values($intOrConstNumericString)); // could have only "int" key
assertType("non-empty-array<int|string, int<1, max>>", array_count_values($intOrConstNonNumericString));
}
Loading