Repository navigation
Expand file tree
/
Copy pathArrayAccessOffsetExistsMethodTypeSpecifyingExtension.php
More file actions
88 lines (73 loc) · 2.35 KB
/
Copy pathArrayAccessOffsetExistsMethodTypeSpecifyingExtension.php
File metadata and controls
88 lines (73 loc) · 2.35 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use ArrayAccess;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
use PHPStan\Analyser\TypeSpecifierAwareExtension;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\Accessory\HasOffsetValueType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\MethodTypeSpecifyingExtension;
use function count;
#[AutowiredService]
final class ArrayAccessOffsetExistsMethodTypeSpecifyingExtension implements MethodTypeSpecifyingExtension, TypeSpecifierAwareExtension
{
private TypeSpecifier $typeSpecifier;
public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
{
$this->typeSpecifier = $typeSpecifier;
}
public function getClass(): string
{
return ArrayAccess::class;
}
public function isMethodSupported(
MethodReflection $methodReflection,
MethodCall $node,
TypeSpecifierContext $context,
): bool
{
return $methodReflection->getName() === 'offsetExists' && $context->true();
}
public function specifyTypes(MethodReflection $methodReflection, MethodCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
{
if (count($node->getArgs()) < 1) {
return new SpecifiedTypes();
}
$key = $node->getArgs()[0]->value;
$keyType = $scope->getType($key);
if (
!$keyType instanceof ConstantStringType
&& !$keyType instanceof ConstantIntegerType
) {
return new SpecifiedTypes();
}
foreach ($scope->getType($node->var)->getObjectClassReflections() as $classReflection) {
$implementsTags = $classReflection->getImplementsTags();
if (
!isset($implementsTags[ArrayAccess::class])
|| !$implementsTags[ArrayAccess::class]->getType() instanceof GenericObjectType
) {
continue;
}
$implementsType = $implementsTags[ArrayAccess::class]->getType();
$arrayAccessGenericTypes = $implementsType->getTypes();
if (!isset($arrayAccessGenericTypes[1])) {
continue;
}
return $this->typeSpecifier->create(
$node->var,
new HasOffsetValueType($keyType, $arrayAccessGenericTypes[1]),
$context,
$scope,
);
}
return new SpecifiedTypes();
}
}