-
-
Notifications
You must be signed in to change notification settings - Fork 440
Expand file tree
/
Copy pathDirnameDirConcatStringToDirectStringPathRector.php
More file actions
99 lines (85 loc) · 2.46 KB
/
DirnameDirConcatStringToDirectStringPathRector.php
File metadata and controls
99 lines (85 loc) · 2.46 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
95
96
97
98
99
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\Concat;
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Scalar\MagicConst\Dir;
use PhpParser\Node\Scalar\String_;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodeQuality\Rector\Concat\DirnameDirConcatStringToDirectStringPathRector\DirnameDirConcatStringToDirectStringPathRectorTest
*/
final class DirnameDirConcatStringToDirectStringPathRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change dirname() and string concat, to __DIR__ and direct string path', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run()
{
$path = dirname(__DIR__) . '/vendor/autoload.php';
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run()
{
$path = __DIR__ . '/../vendor/autoload.php';
}
}
CODE_SAMPLE
),
]);
}
public function getNodeTypes(): array
{
return [Concat::class];
}
/**
* @param Concat $node
*/
public function refactor(Node $node): ?Concat
{
if (! $node->left instanceof FuncCall || ! $this->isName($node->left, 'dirname')) {
return null;
}
if (! $node->right instanceof String_) {
return null;
}
$dirnameFuncCall = $node->left;
if ($dirnameFuncCall->isFirstClassCallable()) {
return null;
}
// avoid multiple dir nesting for now
if (count($dirnameFuncCall->getArgs()) !== 1) {
return null;
}
$firstArg = $dirnameFuncCall->getArgs()[0];
if (! $firstArg->value instanceof Dir) {
return null;
}
$string = $node->right;
if (str_contains($string->value, '/')) {
// linux paths
$string->value = '/../' . ltrim($string->value, '/');
$node->left = new Dir();
return $node;
}
if (str_contains($string->value, '\\')) {
// windows paths
$string->value = '\\..\\' . ltrim($string->value, '\\');
$node->left = new Dir();
return $node;
}
return null;
}
}