forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayMapFunctionReturnTypeExtension.php
84 lines (72 loc) · 2.63 KB
/
ArrayMapFunctionReturnTypeExtension.php
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
class ArrayMapFunctionReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'array_map';
}
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
if (count($functionCall->args) < 2) {
return ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType();
}
$valueType = new MixedType();
$callableType = $scope->getType($functionCall->args[0]->value);
if ($callableType->isCallable()->yes()) {
$valueType = new NeverType();
foreach ($callableType->getCallableParametersAcceptors($scope) as $parametersAcceptor) {
$valueType = TypeCombinator::union($valueType, $parametersAcceptor->getReturnType());
}
}
$mappedArrayType = new ArrayType(
new MixedType(),
$valueType
);
$arrayType = $scope->getType($functionCall->args[1]->value);
$constantArrays = TypeUtils::getConstantArrays($arrayType);
if (!isset($functionCall->args[2])) {
if (count($constantArrays) > 0) {
$arrayTypes = [];
foreach ($constantArrays as $constantArray) {
$returnedArrayBuilder = ConstantArrayTypeBuilder::createEmpty();
foreach ($constantArray->getKeyTypes() as $keyType) {
$returnedArrayBuilder->setOffsetValueType(
$keyType,
$valueType
);
}
$arrayTypes[] = $returnedArrayBuilder->getArray();
}
$mappedArrayType = TypeCombinator::union(...$arrayTypes);
} elseif ($arrayType->isArray()->yes()) {
$mappedArrayType = TypeCombinator::intersect(new ArrayType(
$arrayType->getIterableKeyType(),
$valueType
), ...TypeUtils::getAccessoryTypes($arrayType));
}
} else {
$mappedArrayType = TypeCombinator::intersect(new ArrayType(
new IntegerType(),
$valueType
), ...TypeUtils::getAccessoryTypes($arrayType));
}
if ($arrayType->isIterableAtLeastOnce()->yes()) {
$mappedArrayType = TypeCombinator::intersect($mappedArrayType, new NonEmptyArrayType());
}
return $mappedArrayType;
}
}