-
Notifications
You must be signed in to change notification settings - Fork 426
/
InArrayFunctionTypeSpecifyingExtension.php
78 lines (65 loc) · 2.21 KB
/
InArrayFunctionTypeSpecifyingExtension.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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
use PHPStan\Analyser\TypeSpecifierAwareExtension;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\FunctionTypeSpecifyingExtension;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use function count;
use function strtolower;
class InArrayFunctionTypeSpecifyingExtension implements FunctionTypeSpecifyingExtension, TypeSpecifierAwareExtension
{
private TypeSpecifier $typeSpecifier;
public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
{
$this->typeSpecifier = $typeSpecifier;
}
public function isFunctionSupported(FunctionReflection $functionReflection, FuncCall $node, TypeSpecifierContext $context): bool
{
return strtolower($functionReflection->getName()) === 'in_array'
&& !$context->null();
}
public function specifyTypes(FunctionReflection $functionReflection, FuncCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
{
if (count($node->getArgs()) < 3) {
return new SpecifiedTypes();
}
$strictNodeType = $scope->getType($node->getArgs()[2]->value);
if (!(new ConstantBooleanType(true))->isSuperTypeOf($strictNodeType)->yes()) {
return new SpecifiedTypes([], []);
}
$arrayType = $scope->getType($node->getArgs()[1]->value);
$arrayValueType = $arrayType->getIterableValueType();
$specifiedTypes = new SpecifiedTypes([], []);
if ($context->true()) {
$arrayType = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$node->getArgs()[1]->value,
$arrayType,
$context,
false,
$scope,
));
}
if (
$context->truthy()
|| count(TypeUtils::getConstantScalars($arrayValueType)) > 0
) {
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$node->getArgs()[0]->value,
$arrayValueType,
$context,
false,
$scope,
));
}
return $specifiedTypes;
}
}