-
Notifications
You must be signed in to change notification settings - Fork 428
/
ArrayMergeFunctionDynamicReturnTypeExtension.php
74 lines (60 loc) · 2.02 KB
/
ArrayMergeFunctionDynamicReturnTypeExtension.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
<?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\ConstantArrayType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\GeneralizePrecision;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
class ArrayMergeFunctionDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'array_merge';
}
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
if (!isset($functionCall->getArgs()[0])) {
return ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType();
}
$keyTypes = [];
$valueTypes = [];
$nonEmpty = false;
foreach ($functionCall->getArgs() as $arg) {
$argType = $scope->getType($arg->value);
if ($arg->unpack) {
$argType = $argType->getIterableValueType();
if ($argType instanceof UnionType) {
foreach ($argType->getTypes() as $innerType) {
$argType = $innerType;
}
}
}
$keyTypes[] = $argType->getIterableKeyType()->generalize(GeneralizePrecision::moreSpecific());
$valueTypes[] = $argType->getIterableValueType();
if (!$argType->isIterableAtLeastOnce()->yes()) {
continue;
}
$nonEmpty = true;
}
$keyType = TypeCombinator::union(...$keyTypes);
if ($keyType instanceof NeverType && !$keyType->isExplicit()) {
return new ConstantArrayType([], []);
}
$arrayType = new ArrayType(
$keyType,
TypeCombinator::union(...$valueTypes),
);
if ($nonEmpty) {
$arrayType = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
}
return $arrayType;
}
}