-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathNullableObjectAssignCollector.php
More file actions
78 lines (63 loc) · 2.27 KB
/
NullableObjectAssignCollector.php
File metadata and controls
78 lines (63 loc) · 2.27 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
<?php
declare(strict_types=1);
namespace Rector\PHPUnit\CodeQuality\NodeAnalyser;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeCombinator;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
use Rector\PHPUnit\CodeQuality\ValueObject\VariableNameToType;
use Rector\PHPUnit\CodeQuality\ValueObject\VariableNameToTypeCollection;
/**
* We look for object|null type on the left:
*
* $value = $this->getSomething();
*/
final readonly class NullableObjectAssignCollector
{
public function __construct(
private NodeNameResolver $nodeNameResolver,
private NodeTypeResolver $nodeTypeResolver,
) {
}
public function collect(ClassMethod|Foreach_ $stmtsAware): VariableNameToTypeCollection
{
$variableNamesToType = [];
// first round to collect assigns
foreach ((array) $stmtsAware->stmts as $stmt) {
if (! $stmt instanceof Expression) {
return new VariableNameToTypeCollection([]);
}
if (! $stmt->expr instanceof Assign) {
continue;
}
$variableNameToType = $this->collectFromAssign($stmt->expr);
if (! $variableNameToType instanceof VariableNameToType) {
continue;
}
$variableNamesToType[] = $variableNameToType;
}
return new VariableNameToTypeCollection($variableNamesToType);
}
private function collectFromAssign(Assign $assign): ?VariableNameToType
{
if (! $assign->expr instanceof MethodCall) {
return null;
}
if (! $assign->var instanceof Variable) {
return null;
}
$variableType = $this->nodeTypeResolver->getType($assign);
$bareVariableType = TypeCombinator::removeNull($variableType);
if (! $bareVariableType instanceof ObjectType) {
return null;
}
$variableName = $this->nodeNameResolver->getName($assign->var);
return new VariableNameToType($variableName, $bareVariableType->getClassName());
}
}