-
Notifications
You must be signed in to change notification settings - Fork 574
Expand file tree
/
Copy pathClassExistsFunctionTypeSpecifyingExtension.php
More file actions
81 lines (71 loc) · 2.34 KB
/
ClassExistsFunctionTypeSpecifyingExtension.php
File metadata and controls
81 lines (71 loc) · 2.34 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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar\String_;
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\Node\Expr\AlwaysRememberedExpr;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\BooleanType;
use PHPStan\Type\ClassStringType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\FunctionTypeSpecifyingExtension;
use PHPStan\Type\Generic\GenericClassStringType;
use PHPStan\Type\ObjectType;
use function in_array;
use function ltrim;
#[AutowiredService]
final class ClassExistsFunctionTypeSpecifyingExtension implements FunctionTypeSpecifyingExtension, TypeSpecifierAwareExtension
{
private TypeSpecifier $typeSpecifier;
public function isFunctionSupported(
FunctionReflection $functionReflection,
FuncCall $node,
TypeSpecifierContext $context,
): bool
{
return in_array($functionReflection->getName(), [
'class_exists',
'interface_exists',
'trait_exists',
'enum_exists',
], true) && isset($node->getArgs()[0]) && $context->true();
}
public function specifyTypes(FunctionReflection $functionReflection, FuncCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
{
$args = $node->getArgs();
$argType = $scope->getType($args[0]->value);
if ($argType instanceof ConstantStringType) {
$funcCall = new FuncCall(new FullyQualified('class_exists'), [
new Arg(new String_(ltrim($argType->getValue(), '\\'))),
]);
return $this->typeSpecifier->create(
new AlwaysRememberedExpr($funcCall, new BooleanType(), new BooleanType()),
new ConstantBooleanType(true),
$context,
$scope,
);
}
$narrowedType = new ClassStringType();
if ($functionReflection->getName() === 'enum_exists') {
$narrowedType = new GenericClassStringType(new ObjectType('UnitEnum'));
}
return $this->typeSpecifier->create(
$args[0]->value,
$narrowedType,
$context,
$scope,
);
}
public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
{
$this->typeSpecifier = $typeSpecifier;
}
}