From 1a74c21859ddae43602b990097f36a2f8cefb356 Mon Sep 17 00:00:00 2001 From: Christian Fritsch Date: Wed, 9 Nov 2022 14:39:38 +0100 Subject: [PATCH] Use this->t instead of t --- .../BestPractice/UseThisTInsteadOfTRector.php | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/Rector/BestPractice/UseThisTInsteadOfTRector.php diff --git a/src/Rector/BestPractice/UseThisTInsteadOfTRector.php b/src/Rector/BestPractice/UseThisTInsteadOfTRector.php new file mode 100644 index 00000000..4a6190ad --- /dev/null +++ b/src/Rector/BestPractice/UseThisTInsteadOfTRector.php @@ -0,0 +1,80 @@ +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> + */ + 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; + } +}