-
-
Notifications
You must be signed in to change notification settings - Fork 688
/
CleanupUnneededNullsafeOperatorRector.php
96 lines (90 loc) · 2.64 KB
/
CleanupUnneededNullsafeOperatorRector.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
92
93
94
95
96
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\Rector\NullsafeMethodCall;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\NullsafeMethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PHPStan\Type\ObjectType;
use Rector\Rector\AbstractRector;
use Rector\TypeDeclaration\TypeAnalyzer\ReturnStrictTypeAnalyzer;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see https://wiki.php.net/rfc/nullsafe_operator
*
* @see \Rector\Tests\CodeQuality\Rector\NullsafeMethodCall\CleanupUnneededNullsafeOperatorRector\CleanupUnneededNullsafeOperatorRectorTest
*/
final class CleanupUnneededNullsafeOperatorRector extends AbstractRector implements MinPhpVersionInterface
{
/**
* @readonly
*/
private ReturnStrictTypeAnalyzer $returnStrictTypeAnalyzer;
public function __construct(ReturnStrictTypeAnalyzer $returnStrictTypeAnalyzer)
{
$this->returnStrictTypeAnalyzer = $returnStrictTypeAnalyzer;
}
public function getRuleDefinition() : RuleDefinition
{
return new RuleDefinition('Cleanup unneeded nullsafe operator', [new CodeSample(<<<'CODE_SAMPLE'
class HelloWorld {
public function getString(): string
{
return 'hello world';
}
}
function get(): HelloWorld
{
return new HelloWorld();
}
echo get()?->getString();
CODE_SAMPLE
, <<<'CODE_SAMPLE'
class HelloWorld {
public function getString(): string
{
return 'hello world';
}
}
function get(): HelloWorld
{
return new HelloWorld();
}
echo get()->getString();
CODE_SAMPLE
)]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [NullsafeMethodCall::class];
}
/**
* @param NullsafeMethodCall $node
*/
public function refactor(Node $node) : ?Node
{
if (!$node->name instanceof Identifier) {
return null;
}
if (!$node->var instanceof FuncCall && !$node->var instanceof MethodCall && !$node->var instanceof StaticCall) {
return null;
}
$returnType = $this->returnStrictTypeAnalyzer->resolveMethodCallReturnType($node->var);
if (!$returnType instanceof ObjectType) {
return null;
}
return new MethodCall($node->var, $node->name, $node->args);
}
public function provideMinPhpVersion() : int
{
return PhpVersionFeature::NULLSAFE_OPERATOR;
}
}