|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\PHPUnit\CodeQuality\Rector\ClassMethod; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Stmt\ClassMethod; |
| 9 | +use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer; |
| 10 | +use Rector\Rector\AbstractRector; |
| 11 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 12 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 13 | + |
| 14 | +/** |
| 15 | + * @see \Rector\PHPUnit\Tests\CodeQuality\Rector\ClassMethod\PreferTestsWithSnakeCaseRector\PreferTestsWithSnakeCaseRectorTest |
| 16 | + */ |
| 17 | +final class PreferTestsWithSnakeCaseRector extends AbstractRector |
| 18 | +{ |
| 19 | + public function __construct( |
| 20 | + private readonly TestsNodeAnalyzer $testsNodeAnalyzer, |
| 21 | + ) { |
| 22 | + } |
| 23 | + |
| 24 | + public function getRuleDefinition(): RuleDefinition |
| 25 | + { |
| 26 | + return new RuleDefinition('Changes PHPUnit tests methods to snake case', [ |
| 27 | + new CodeSample( |
| 28 | + <<<'CODE_SAMPLE' |
| 29 | +use PHPUnit\Framework\TestCase; |
| 30 | +
|
| 31 | +final class SomeClass extends TestCase |
| 32 | +{ |
| 33 | + public function testSomething() |
| 34 | + { |
| 35 | + } |
| 36 | +} |
| 37 | +CODE_SAMPLE |
| 38 | + , |
| 39 | + <<<'CODE_SAMPLE' |
| 40 | +use PHPUnit\Framework\TestCase; |
| 41 | +
|
| 42 | +final class SomeClass extends TestCase |
| 43 | +{ |
| 44 | + public function test_something() |
| 45 | + { |
| 46 | + } |
| 47 | +} |
| 48 | +CODE_SAMPLE |
| 49 | + ), |
| 50 | + ]); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @return array<class-string<Node>> |
| 55 | + */ |
| 56 | + public function getNodeTypes(): array |
| 57 | + { |
| 58 | + return [ClassMethod::class]; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @param ClassMethod $node |
| 63 | + */ |
| 64 | + public function refactor(Node $node): ?Node |
| 65 | + { |
| 66 | + if (! $this->testsNodeAnalyzer->isInTestClass($node)) { |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + if (! $this->testsNodeAnalyzer->isTestClassMethod($node)) { |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + $currentName = $node->name->toString(); |
| 75 | + $newName = $this->toSnakeCase($currentName); |
| 76 | + |
| 77 | + if ($currentName === $newName) { |
| 78 | + return null; |
| 79 | + } |
| 80 | + |
| 81 | + $node->name = new Node\Identifier($newName); |
| 82 | + |
| 83 | + return $node; |
| 84 | + } |
| 85 | + |
| 86 | + public function toSnakeCase(string $value): string |
| 87 | + { |
| 88 | + if (ctype_lower($value)) { |
| 89 | + return $value; |
| 90 | + } |
| 91 | + |
| 92 | + $value = (string) preg_replace('/\s+/u', '', ucwords($value)); |
| 93 | + $value = (string) preg_replace('/(.)(?=[A-Z])/u', '$1_', $value); |
| 94 | + |
| 95 | + return strtolower($value); |
| 96 | + } |
| 97 | +} |
0 commit comments