Repository navigation
Expand file tree
/
Copy pathArrayMapCallbackParameterTypes.php
More file actions
70 lines (58 loc) · 1.78 KB
/
Copy pathArrayMapCallbackParameterTypes.php
File metadata and controls
70 lines (58 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php declare(strict_types = 1);
namespace PHPStan\Reflection;
use PHPStan\Turbo\ReferencedByTurboExtension;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function count;
use function is_int;
use function max;
/**
* With more than one array, array_map() calls the callback once per index of
* the longest array, and passes null for each array that is shorter.
*/
#[ReferencedByTurboExtension(key: 'arrayMapCallbackParameterTypes')]
final class ArrayMapCallbackParameterTypes
{
/**
* Adds null to the value type of each array that is shorter than another one
* when both have their largest size. Only when the size of every array is known.
*
* The largest sizes are compared, not the smallest, because two arrays can be
* one array: array_map($cb, $a, $a) never passes null, whatever sizes $a can have.
*
* @param list<Type> $valueTypes
* @param list<Type> $arrayTypes the array each value type comes from
* @return list<Type>
*/
public static function addPaddingNull(array $valueTypes, array $arrayTypes): array
{
if (count($arrayTypes) < 2) {
return $valueTypes;
}
$maxSizes = [];
foreach ($arrayTypes as $i => $arrayType) {
$sizes = [];
foreach ($arrayType->getArraySize()->getFiniteTypes() as $sizeType) {
foreach ($sizeType->getConstantScalarValues() as $size) {
if (!is_int($size)) {
continue;
}
$sizes[] = $size;
}
}
if ($sizes === []) {
// general arrays can have the same size, but the type system cannot say so
return $valueTypes;
}
$maxSizes[$i] = max($sizes);
}
$longestSize = max($maxSizes);
foreach ($valueTypes as $i => $valueType) {
if ($maxSizes[$i] === $longestSize) {
continue;
}
$valueTypes[$i] = TypeCombinator::addNull($valueType);
}
return $valueTypes;
}
}