Skip to content

Commit

Permalink
Use this->t instead of t
Browse files Browse the repository at this point in the history
  • Loading branch information
Christian Fritsch committed Nov 9, 2022
1 parent 02e8ee4 commit 1a74c21
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions src/Rector/BestPractice/UseThisTInsteadOfTRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

declare(strict_types=1);

namespace DrupalRector\Rector\BestPractice;

use PhpParser\Node;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use PhpParser\Node\Expr\FuncCall;
use Rector\NodeTypeResolver\Node\AttributeKey;
use PhpParser\Node\Stmt\Class_;

/**
* Replaces t() with $this->t().
*/
final class UseThisTInsteadOfTRector extends AbstractRector
{

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Turns static t calls into $this->t.',
[
new ConfiguredCodeSample(
't("Text");',
'$this->t("Text");',
['t' => '$this->t']
),
]
);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}

/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
if (!$this->isName($node, 't')) {
return null;
}

// not to refactor here
$isVirtual = (bool)$node->name->getAttribute(
AttributeKey::VIRTUAL_NODE
);
if ($isVirtual) {
return null;
}

$parentFunction = $this->betterNodeFinder->findParentType($node, Node\Stmt\ClassMethod::class);
if (!$parentFunction instanceof Node\Stmt\ClassMethod || $parentFunction->isStatic()) {
return null;
}

$class = $this->betterNodeFinder->findParentType($node, Class_::class);
if (!$class instanceof Class_) {
return null;
}

$className = (string) $this->nodeNameResolver->getName($class);
if (method_exists($className, 't')) {
return new Node\Expr\MethodCall(
new Node\Expr\Variable('this'),
't',
$node->args
);
}
return null;
}
}

0 comments on commit 1a74c21

Please sign in to comment.