Skip to content

Commit 9ed20e0

Browse files
committed
Describe built-in functions that walk nested arrays with recursive types
mb_check_encoding() and mb_convert_encoding() take nested arrays of scalars and nulls, and compact() nested arrays of variable names, at any depth. The callback of array_walk_recursive() gets the values that are not arrays at any depth, with their keys. filter_var() and the other filter functions with FILTER_REQUIRE_ARRAY or FILTER_FORCE_ARRAY filter the values of nested arrays at any depth and keep the arrays, when the input is known to contain them; an array of mixed is left as it was. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 1f42eab commit 9ed20e0

7 files changed

Lines changed: 211 additions & 7 deletions

File tree

‎resources/functionMap.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -970,7 +970,7 @@
970970
'com_message_pump' => ['bool', 'timeoutms='=>'int'],
971971
'com_print_typeinfo' => ['bool', 'comobject_or_typelib'=>'object', 'dispinterface='=>'string', 'wantsink='=>'bool'],
972972
'com_release' => [''],
973-
'compact' => ['array<string, mixed>', '...var_names='=>'string|array'],
973+
'compact' => ['array<string, mixed>', 'var_name'=>'string|__recursive<array<string|__recursion>>', '...var_names='=>'string|__recursive<array<string|__recursion>>'],
974974
'COMPersistHelper::__construct' => ['void', 'com_object'=>'object'],
975975
'COMPersistHelper::GetCurFile' => ['string'],
976976
'COMPersistHelper::GetMaxStreamSize' => ['int'],
@@ -5734,8 +5734,8 @@
57345734
'maxdb_thread_safe' => ['bool'],
57355735
'maxdb_use_result' => ['resource', 'link'=>''],
57365736
'maxdb_warning_count' => ['int', 'link'=>'resource'],
5737-
'mb_check_encoding' => ['bool', 'var='=>'string|array<string>', 'encoding='=>'string'],
5738-
'mb_convert_encoding' => ['string|array|false', 'val'=>'string|array', 'to_encoding'=>'string', 'from_encoding='=>'mixed'],
5737+
'mb_check_encoding' => ['bool', 'var='=>'string|__recursive<array<scalar|null|__recursion>>', 'encoding='=>'string'],
5738+
'mb_convert_encoding' => ['string|array|false', 'val'=>'string|__recursive<array<scalar|null|__recursion>>', 'to_encoding'=>'string', 'from_encoding='=>'mixed'],
57395739
'mb_convert_variables' => ['string|false', 'to_encoding'=>'string', 'from_encoding'=>'array|string', '&rw_vars'=>'string|array|object', '&...rw_vars='=>'string|array|object'],
57405740
'mb_decode_mimeheader' => ['string', 'string'=>'string'],
57415741
'mb_decode_numericentity' => ['string', 'string'=>'string', 'convmap'=>'array', 'encoding'=>'string'],

‎src/Type/Php/ArrayWalkParameterClosureTypeExtension.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,15 @@
1414
use PHPStan\Type\FunctionParameterClosureTypeExtension;
1515
use PHPStan\Type\MixedType;
1616
use PHPStan\Type\Type;
17+
use function in_array;
1718

1819
#[AutowiredService]
1920
final class ArrayWalkParameterClosureTypeExtension implements FunctionParameterClosureTypeExtension
2021
{
2122

2223
public function isFunctionSupported(FunctionReflection $functionReflection, ParameterReflection $parameter): bool
2324
{
24-
return $functionReflection->getName() === 'array_walk' && $parameter->getName() === 'callback';
25+
return in_array($functionReflection->getName(), ['array_walk', 'array_walk_recursive'], true) && $parameter->getName() === 'callback';
2526
}
2627

2728
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, ParameterReflection $parameter, Scope $scope): ?Type
@@ -32,9 +33,16 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
3233
}
3334

3435
$arrayType = $scope->getType($args[0]->value);
36+
if ($functionReflection->getName() === 'array_walk_recursive' && $arrayType->isArray()->yes()) {
37+
// the callback is called with the values that are not arrays, at any depth
38+
[$keyType, $valueType] = NestedArrayLeaves::get($arrayType);
39+
} else {
40+
$keyType = $scope->getIterableKeyType($arrayType);
41+
$valueType = $scope->getIterableValueType($arrayType);
42+
}
3543
$parameters = [
36-
new NativeParameterReflection('item', false, $scope->getIterableValueType($arrayType), PassedByReference::createReadsArgument(), false, null),
37-
new NativeParameterReflection('key', false, $scope->getIterableKeyType($arrayType), PassedByReference::createNo(), false, null),
44+
new NativeParameterReflection('item', false, $valueType, PassedByReference::createReadsArgument(), false, null),
45+
new NativeParameterReflection('key', false, $keyType, PassedByReference::createNo(), false, null),
3846
];
3947
if (isset($args[2])) {
4048
$parameters[] = new NativeParameterReflection('arg', false, $scope->getType($args[2]->value), PassedByReference::createNo(), false, null);

‎src/Type/Php/FilterFunctionReturnTypeHelper.php‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
use PHPStan\Type\MixedType;
2424
use PHPStan\Type\NeverType;
2525
use PHPStan\Type\NullType;
26+
use PHPStan\Type\RecursiveType;
27+
use PHPStan\Type\RecursiveTypeReference;
2628
use PHPStan\Type\StringType;
2729
use PHPStan\Type\Type;
2830
use PHPStan\Type\TypeCombinator;
@@ -169,9 +171,18 @@ public function getType(Type $inputType, ?Type $filterType, ?Type $flagsType, Ph
169171
return $mixedType;
170172
}
171173

174+
$nestedArraysPossible = false;
172175
if ($inputIsArray->yes() && ($hasRequireArrayFlag->yes() || $hasForceArrayFlag->yes())) {
173176
$inputArrayKeyType = $inputType->getIterableKeyType();
174-
$inputType = $inputType->getIterableValueType();
177+
// the filter is applied to the values that are not arrays, at any depth,
178+
// and the nested arrays are kept; an array of mixed is left to level 9
179+
$inputValueType = $inputType->getIterableValueType();
180+
if (!$inputValueType instanceof MixedType && !$inputValueType->isArray()->no()) {
181+
$nestedArraysPossible = true;
182+
[, $inputType] = NestedArrayLeaves::get($inputType);
183+
} else {
184+
$inputType = $inputValueType;
185+
}
175186
}
176187

177188
if ($inputType->isScalar()->no() && $inputType->isNull()->no()) {
@@ -205,6 +216,15 @@ public function getType(Type $inputType, ?Type $filterType, ?Type $flagsType, Ph
205216
$type = TypeCombinator::remove($type, $defaultType);
206217
}
207218

219+
if ($nestedArraysPossible) {
220+
$reference = new RecursiveTypeReference('#1', null);
221+
$type = TypeCombinator::union($type, new RecursiveType(
222+
new ArrayType(new UnionType([new IntegerType(), new StringType()]), TypeCombinator::union($type, $reference)),
223+
'#1',
224+
null,
225+
));
226+
}
227+
208228
if ($hasRequireArrayFlag->yes()) {
209229
$type = new ArrayType($inputArrayKeyType ?? $mixedType, $type);
210230
if (!$hasThrowOnFailureFlag->yes() && !$inputIsArray->yes()) {

‎src/Type/Php/NestedArrayLeaves.php‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Type\Php;
4+
5+
use PHPStan\Type\ArrayType;
6+
use PHPStan\Type\MixedType;
7+
use PHPStan\Type\NeverType;
8+
use PHPStan\Type\Type;
9+
use PHPStan\Type\TypeCombinator;
10+
use function array_pop;
11+
12+
/**
13+
* The values that are not arrays at any depth of a nested array, and their keys,
14+
* which is what functions that walk nested arrays like array_walk_recursive()
15+
* and filter_var() with FILTER_REQUIRE_ARRAY take one by one.
16+
*/
17+
final class NestedArrayLeaves
18+
{
19+
20+
/**
21+
* @return array{Type, Type} the key type and the value type of the leaves
22+
*/
23+
public static function get(Type $arrayType): array
24+
{
25+
$anyArray = new ArrayType(new MixedType(), new MixedType());
26+
$keyTypes = [];
27+
$leafTypes = [];
28+
$visited = [];
29+
$pending = [$arrayType];
30+
while ($pending !== []) {
31+
$type = array_pop($pending);
32+
foreach ($visited as $visitedType) {
33+
if ($visitedType->equals($type)) {
34+
continue 2;
35+
}
36+
}
37+
$visited[] = $type;
38+
39+
$valueType = $type->getIterableValueType();
40+
$keyTypes[] = $type->getIterableKeyType();
41+
$leafTypes[] = TypeCombinator::remove($valueType, $anyArray);
42+
$nestedType = TypeCombinator::intersect($valueType, $anyArray);
43+
if ($nestedType instanceof NeverType) {
44+
continue;
45+
}
46+
47+
$pending[] = $nestedType;
48+
}
49+
50+
return [TypeCombinator::union(...$keyTypes), TypeCombinator::union(...$leafTypes)];
51+
}
52+
53+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace RecursiveBuiltinFunctions;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
class Foo
10+
{
11+
12+
/**
13+
* @param array<string, int|array<string, float|array<string, bool>>> $nested
14+
* @param array<string, int> $flat
15+
* @param array<string, mixed> $mixedValues
16+
*/
17+
public function walk(array $nested, array $flat, array $mixedValues): void
18+
{
19+
array_walk_recursive($nested, function ($value, $key): void {
20+
assertType('bool|float|int', $value);
21+
assertType('string', $key);
22+
});
23+
array_walk_recursive($flat, function ($value, $key): void {
24+
assertType('int', $value);
25+
assertType('string', $key);
26+
});
27+
$constant = [1, [2, ['x' => 'y']]];
28+
array_walk_recursive($constant, function ($value, $key): void {
29+
assertType("1|2|'y'", $value);
30+
assertType("0|1|'x'", $key);
31+
});
32+
array_walk_recursive($mixedValues, function ($value): void {
33+
assertType('mixed~array', $value);
34+
});
35+
array_walk_recursive($nested, function ($value, $key, $arg): void {
36+
assertType("'extra'", $arg);
37+
}, 'extra');
38+
}
39+
40+
/**
41+
* @param array<string, int|array<string, int>> $nested
42+
* @param array<string, int> $flat
43+
* @param array<string, mixed> $mixedValues
44+
*/
45+
public function filter(array $nested, array $flat, array $mixedValues, mixed $mixed): void
46+
{
47+
// nested arrays are filtered at every depth and kept
48+
assertType('array<string, __recursive<array<int|string, __recursion|int>>|int>', filter_var($nested, FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY));
49+
assertType('array<string, __recursive<array<int|string, __recursion|int>>|int>', filter_var($nested, FILTER_VALIDATE_INT, FILTER_FORCE_ARRAY));
50+
assertType('array<string, int>', filter_var($flat, FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY));
51+
// an array of mixed and mixed are left as they were
52+
assertType('array<string, int|false>', filter_var($mixedValues, FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY));
53+
assertType('array<int|false>|false', filter_var($mixed, FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY));
54+
}
55+
56+
}

‎tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3994,4 +3994,34 @@ public function testRecursiveTypes(): void
39943994
]);
39953995
}
39963996

3997+
#[RequiresPhp('>= 8.0.0')]
3998+
public function testRecursiveBuiltinParameters(): void
3999+
{
4000+
$errors = [
4001+
[
4002+
'Parameter #1 $value of function mb_check_encoding expects array<*RECURSION*|bool|float|int|string|null>|string|null, array<string, array<int, RecursiveBuiltinParameters\\Obj>> given.',
4003+
18,
4004+
],
4005+
[
4006+
'Parameter #1 $string of function mb_convert_encoding expects array<*RECURSION*|bool|float|int|string|null>|string, array<string, array<string, RecursiveBuiltinParameters\\Obj>> given.',
4007+
21,
4008+
],
4009+
[
4010+
'Parameter #2 ...$var_names of function compact expects array<*RECURSION*|string>|string, array<int, list<int>|string> given.',
4011+
25,
4012+
],
4013+
];
4014+
if (PHP_VERSION_ID >= 80600) {
4015+
$errors[] = [
4016+
'Parameter #1 $array of function array_walk_recursive expects array, array<string, list<int>>|RecursiveBuiltinParameters\\Obj given.',
4017+
34,
4018+
];
4019+
}
4020+
$errors[] = [
4021+
'Parameter #1 $string of function strlen expects string, list<int> given.',
4022+
35,
4023+
];
4024+
$this->analyse([__DIR__ . '/data/recursive-builtin-parameters.php'], $errors);
4025+
}
4026+
39974027
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace RecursiveBuiltinParameters;
4+
5+
class Obj
6+
{
7+
8+
}
9+
10+
/**
11+
* @param array<string, string|int|array<string, string|null>> $nested
12+
*/
13+
function doFoo(array $nested, string $s): void
14+
{
15+
// mb_check_encoding() checks nested arrays, and passes over ints, floats, bools and nulls
16+
mb_check_encoding(['a' => ['b' => 'c', 'd' => 1, 'e' => null]], 'UTF-8');
17+
mb_check_encoding($nested, 'UTF-8');
18+
mb_check_encoding(['a' => [new Obj()]], 'UTF-8');
19+
20+
mb_convert_encoding(['a' => ['b' => 'c', 'd' => 1.5]], 'UTF-8');
21+
mb_convert_encoding(['a' => ['b' => new Obj()]], 'UTF-8');
22+
23+
// compact() takes nested arrays of variable names
24+
compact('s', ['nested', ['s']]);
25+
compact('s', ['nested', [1]]);
26+
}
27+
28+
/**
29+
* @param array<string, list<int>>|Obj $maybeArray
30+
*/
31+
function walk($maybeArray): void
32+
{
33+
// what may not be an array is walked like array_walk() does
34+
array_walk_recursive($maybeArray, function ($value): void {
35+
strlen($value);
36+
});
37+
}

0 commit comments

Comments
 (0)