forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayReduceCallbackClosureTypeExtension.php
More file actions
67 lines (55 loc) · 2.17 KB
/
ArrayReduceCallbackClosureTypeExtension.php
File metadata and controls
67 lines (55 loc) · 2.17 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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\Native\NativeParameterReflection;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\Type\ClosureType;
use PHPStan\Type\FunctionParameterClosureTypeExtension;
use PHPStan\Type\GeneralizePrecision;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ParserNodeTypeToPHPStanType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
#[AutowiredService]
final class ArrayReduceCallbackClosureTypeExtension implements FunctionParameterClosureTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection, ParameterReflection $parameter): bool
{
return $functionReflection->getName() === 'array_reduce' && $parameter->getName() === 'callback';
}
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, ParameterReflection $parameter, Scope $scope): ?Type
{
$args = $functionCall->getArgs();
if (!isset($args[0])) {
return null;
}
$arrayType = $scope->getType($args[0]->value);
$valueType = $arrayType->getIterableValueType();
if (isset($args[2])) {
$initialType = $scope->getType($args[2]->value);
} else {
$initialType = new NullType();
}
$carryType = $initialType->generalize(GeneralizePrecision::templateArgument());
$callbackExpr = $args[1]->value ?? null;
if ($callbackExpr instanceof Closure || $callbackExpr instanceof ArrowFunction) {
$callbackReturnType = ParserNodeTypeToPHPStanType::resolve($callbackExpr->returnType, null);
if (!$callbackReturnType instanceof MixedType) {
$carryType = TypeCombinator::union($carryType, $callbackReturnType);
}
}
return new ClosureType(
[
new NativeParameterReflection('carry', false, $carryType, $parameter->passedByReference(), false, null),
new NativeParameterReflection('value', false, $valueType, $parameter->passedByReference(), false, null),
],
new MixedType(),
);
}
}