forked from rectorphp/rector-symfony
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControllerAnalyzer.php
More file actions
94 lines (76 loc) · 2.61 KB
/
ControllerAnalyzer.php
File metadata and controls
94 lines (76 loc) · 2.61 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
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace Rector\Symfony\TypeAnalyzer;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ThisType;
use PHPStan\Type\TypeWithClassName;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Php80\NodeAnalyzer\PhpAttributeAnalyzer;
use Rector\Reflection\ReflectionResolver;
use Rector\Symfony\Enum\SymfonyAttribute;
use Rector\Symfony\Enum\SymfonyClass;
final class ControllerAnalyzer
{
public function __construct(
private ReflectionResolver $reflectionResolver,
) {
}
public function isController(Expr|Class_ $node): bool
{
if ($node instanceof Class_) {
return $this->isControllerClass($node);
}
$scope = $node->getAttribute(AttributeKey::SCOPE);
// might be missing in a trait
if (! $scope instanceof Scope) {
return false;
}
$nodeType = $scope->getType($node);
if (! $nodeType instanceof TypeWithClassName) {
return false;
}
if ($nodeType instanceof ThisType) {
$nodeType = $nodeType->getStaticObjectType();
}
if (! $nodeType instanceof ObjectType) {
return false;
}
$classReflection = $nodeType->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}
return $this->isControllerClassReflection($classReflection);
}
public function isInsideController(Node $node): bool
{
$classReflection = $this->reflectionResolver->resolveClassReflection($node);
if (! $classReflection instanceof ClassReflection) {
return false;
}
return $this->isControllerClassReflection($classReflection);
}
private function isControllerClassReflection(ClassReflection $classReflection): bool
{
if ($classReflection->is(SymfonyClass::CONTROLLER)) {
return true;
}
foreach ($classReflection->getAttributes() as $attribute) {
if ($attribute->getName() === SymfonyAttribute::AS_CONTROLLER) {
return true;
}
}
return $classReflection->is(SymfonyClass::ABSTRACT_CONTROLLER);
}
private function isControllerClass(Class_ $class): bool
{
$classReflection = $this->reflectionResolver->resolveClassReflection($class);
if (! $classReflection instanceof ClassReflection) {
return false;
}
return $this->isControllerClassReflection($classReflection);
}
}