|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Utils\Rector\Rector; |
| 6 | + |
| 7 | +use Nette\Utils\Strings; |
| 8 | +use PhpParser\Node; |
| 9 | +use PhpParser\Node\Identifier; |
| 10 | +use PhpParser\Node\Expr\MethodCall; |
| 11 | +use Rector\Core\Rector\AbstractRector; |
| 12 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 13 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 14 | + |
| 15 | +final class MyFirstRector extends AbstractRector |
| 16 | +{ |
| 17 | + /** |
| 18 | + * @return array<class-string<Node>> |
| 19 | + */ |
| 20 | + public function getNodeTypes(): array |
| 21 | + { |
| 22 | + // what node types are we looking for? |
| 23 | + // pick any node from https://github.com/rectorphp/php-parser-nodes-docs/ |
| 24 | + return [MethodCall::class]; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * @param MethodCall $node - we can add "MethodCall" type here, because |
| 29 | + * only this node is in "getNodeTypes()" |
| 30 | + */ |
| 31 | + public function refactor(Node $node): ?Node |
| 32 | + { |
| 33 | + // we only care about "set*" method names |
| 34 | + if (! $this->isName($node->name, 'set*')) { |
| 35 | + // return null to skip it |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + $methodCallName = $this->getName($node->name); |
| 40 | + $newMethodCallName = Strings::replace($methodCallName, '#^set#', 'change'); |
| 41 | + |
| 42 | + $node->name = new Identifier($newMethodCallName); |
| 43 | + |
| 44 | + // return $node if you modified it |
| 45 | + return $node; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * This method helps other to understand the rule and to generate documentation. |
| 50 | + */ |
| 51 | + public function getRuleDefinition(): RuleDefinition |
| 52 | + { |
| 53 | + return new RuleDefinition( |
| 54 | + 'Change method calls from set* to change*.', [ |
| 55 | + new CodeSample( |
| 56 | + // code before |
| 57 | + '$user->setPassword("123456");', |
| 58 | + // code after |
| 59 | + '$user->changePassword("123456");' |
| 60 | + ), |
| 61 | + ] |
| 62 | + ); |
| 63 | + } |
| 64 | +} |
0 commit comments