diff --git a/src/Rector/BestPractice/UseThisTInsteadOfTRector.php b/src/Rector/BestPractice/UseThisTInsteadOfTRector.php new file mode 100644 index 00000000..bc1fa2be --- /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; + } +} diff --git a/tests/src/Rector/BestPractive/UseThisTInsteadOfTRector/UseThisTInsteadOfTRectorTest.php b/tests/src/Rector/BestPractive/UseThisTInsteadOfTRector/UseThisTInsteadOfTRectorTest.php new file mode 100644 index 00000000..4a81344f --- /dev/null +++ b/tests/src/Rector/BestPractive/UseThisTInsteadOfTRector/UseThisTInsteadOfTRectorTest.php @@ -0,0 +1,35 @@ +doTestFile($filePath); + } + + /** + * @return Iterator<> + */ + public static function provideData(): \Iterator + { + return self::yieldFilesFromDirectory(__DIR__.'/fixture'); + } + + public function provideConfigFilePath(): string + { + // must be implemented + return __DIR__.'/config/configured_rule.php'; + } +} diff --git a/tests/src/Rector/BestPractive/UseThisTInsteadOfTRector/config/configured_rule.php b/tests/src/Rector/BestPractive/UseThisTInsteadOfTRector/config/configured_rule.php new file mode 100644 index 00000000..4dcbaa07 --- /dev/null +++ b/tests/src/Rector/BestPractive/UseThisTInsteadOfTRector/config/configured_rule.php @@ -0,0 +1,10 @@ + +----- +t('Hello world'); + } + +} + +?>