forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiDirnameRector.php
115 lines (92 loc) · 2.83 KB
/
MultiDirnameRector.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
declare(strict_types=1);
namespace Rector\Php70\Rector\FuncCall;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Scalar\LNumber;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\Php70\Rector\FuncCall\MultiDirnameRector\MultiDirnameRectorTest
*/
final class MultiDirnameRector extends AbstractRector
{
/**
* @var string
*/
private const DIRNAME = 'dirname';
/**
* @var int
*/
private $nestingLevel = 0;
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Changes multiple dirname() calls to one with nesting level',
[new CodeSample('dirname(dirname($path));', 'dirname($path, 2);')]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isAtLeastPhpVersion(PhpVersionFeature::DIRNAME_LEVELS)) {
return null;
}
$this->nestingLevel = 0;
if (! $this->isName($node, self::DIRNAME)) {
return null;
}
$activeFuncCallNode = $node;
$lastFuncCallNode = $node;
while ($activeFuncCallNode = $this->matchNestedDirnameFuncCall($activeFuncCallNode)) {
$lastFuncCallNode = $activeFuncCallNode;
}
// nothing to improve
if ($this->nestingLevel < 2) {
return $activeFuncCallNode;
}
$node->args[0] = $lastFuncCallNode->args[0];
$node->args[1] = new Arg(new LNumber($this->nestingLevel));
return $node;
}
private function matchNestedDirnameFuncCall(FuncCall $funcCall): ?FuncCall
{
if (! $this->isName($funcCall, self::DIRNAME)) {
return null;
}
if (count($funcCall->args) >= 3) {
return null;
}
// dirname($path, <LEVEL>);
if (count($funcCall->args) === 2) {
if (! $funcCall->args[1]->value instanceof LNumber) {
return null;
}
/** @var LNumber $levelNumber */
$levelNumber = $funcCall->args[1]->value;
$this->nestingLevel += $levelNumber->value;
} else {
++$this->nestingLevel;
}
$nestedFuncCallNode = $funcCall->args[0]->value;
if (! $nestedFuncCallNode instanceof FuncCall) {
return null;
}
if ($this->isName($nestedFuncCallNode, self::DIRNAME)) {
return $nestedFuncCallNode;
}
return null;
}
}