-
Notifications
You must be signed in to change notification settings - Fork 426
/
GetClassDynamicReturnTypeExtension.php
91 lines (76 loc) · 2.62 KB
/
GetClassDynamicReturnTypeExtension.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
85
86
87
88
89
90
91
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\ClassStringType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\Enum\EnumCaseObjectType;
use PHPStan\Type\Generic\GenericClassStringType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\StaticType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\UnionType;
use function count;
class GetClassDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'get_class';
}
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
$args = $functionCall->getArgs();
if ($scope->isInTrait()) {
return new StringType();
}
if (count($args) === 0) {
if ($scope->isInClass()) {
return new ConstantStringType($scope->getClassReflection()->getName(), true);
}
return new ConstantBooleanType(false);
}
$argType = $scope->getType($args[0]->value);
return TypeTraverser::map(
$argType,
static function (Type $type, callable $traverse): Type {
if ($type instanceof UnionType || $type instanceof IntersectionType) {
return $traverse($type);
}
if ($type instanceof EnumCaseObjectType) {
return new GenericClassStringType(new ObjectType($type->getClassName()));
}
if ($type instanceof TemplateType && !$type instanceof TypeWithClassName) {
if ($type instanceof ObjectWithoutClassType) {
return new GenericClassStringType($type);
}
return new UnionType([
new GenericClassStringType($type),
new ConstantBooleanType(false),
]);
} elseif ($type instanceof MixedType) {
return new UnionType([
new ClassStringType(),
new ConstantBooleanType(false),
]);
} elseif ($type instanceof StaticType) {
return new GenericClassStringType($type->getStaticObjectType());
} elseif ($type instanceof TypeWithClassName) {
return new GenericClassStringType($type);
} elseif ($type instanceof ObjectWithoutClassType) {
return new ClassStringType();
}
return new ConstantBooleanType(false);
},
);
}
}