Skip to content

Commit a6a1758

Browse files
Christian Fritschbbrala
Christian Fritsch
authored andcommitted
Use this->t instead of t
1 parent 6d3a501 commit a6a1758

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace DrupalRector\Rector\BestPractice;
6+
7+
use PhpParser\Node;
8+
use Rector\Core\Rector\AbstractRector;
9+
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
10+
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
11+
use PhpParser\Node\Expr\FuncCall;
12+
use Rector\NodeTypeResolver\Node\AttributeKey;
13+
use PhpParser\Node\Stmt\Class_;
14+
15+
/**
16+
* Replaces t() with $this->t().
17+
*/
18+
final class UseThisTInsteadOfTRector extends AbstractRector
19+
{
20+
21+
public function getRuleDefinition(): RuleDefinition
22+
{
23+
return new RuleDefinition(
24+
'Turns static t calls into $this->t.',
25+
[
26+
new ConfiguredCodeSample(
27+
't("Text");',
28+
'$this->t("Text");',
29+
['t' => '$this->t']
30+
),
31+
]
32+
);
33+
}
34+
35+
/**
36+
* @return array<class-string<Node>>
37+
*/
38+
public function getNodeTypes(): array
39+
{
40+
return [FuncCall::class];
41+
}
42+
43+
/**
44+
* @param FuncCall $node
45+
*/
46+
public function refactor(Node $node): ?Node
47+
{
48+
if (!$this->isName($node, 't')) {
49+
return null;
50+
}
51+
52+
// not to refactor here
53+
$isVirtual = (bool)$node->name->getAttribute(
54+
AttributeKey::VIRTUAL_NODE
55+
);
56+
if ($isVirtual) {
57+
return null;
58+
}
59+
60+
$parentFunction = $this->betterNodeFinder->findParentType($node, Node\Stmt\ClassMethod::class);
61+
if (!$parentFunction instanceof Node\Stmt\ClassMethod || $parentFunction->isStatic()) {
62+
return null;
63+
}
64+
65+
$class = $this->betterNodeFinder->findParentType($node, Class_::class);
66+
if (!$class instanceof Class_) {
67+
return null;
68+
}
69+
70+
$className = (string) $this->nodeNameResolver->getName($class);
71+
if (method_exists($className, 't')) {
72+
return new Node\Expr\MethodCall(
73+
new Node\Expr\Variable('this'),
74+
't',
75+
$node->args
76+
);
77+
}
78+
return null;
79+
}
80+
}

0 commit comments

Comments
 (0)