|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Rector\PHPUnit\Rector\MethodCall; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\MethodCall; |
| 7 | +use Rector\Rector\AbstractPHPUnitRector; |
| 8 | +use Rector\RectorDefinition\CodeSample; |
| 9 | +use Rector\RectorDefinition\RectorDefinition; |
| 10 | + |
| 11 | +/** |
| 12 | + * @see https://github.com/symfony/symfony/pull/30813/files#r270879504 |
| 13 | + */ |
| 14 | +final class RemoveExpectAnyFromMockRector extends AbstractPHPUnitRector |
| 15 | +{ |
| 16 | + public function getDefinition(): RectorDefinition |
| 17 | + { |
| 18 | + return new RectorDefinition('Remove `expect($this->any())` from mocks as it has no added value', [ |
| 19 | + new CodeSample( |
| 20 | + <<<'CODE_SAMPLE' |
| 21 | +use PHPUnit\Framework\TestCase; |
| 22 | +
|
| 23 | +class SomeClass extends TestCase |
| 24 | +{ |
| 25 | + public function test() |
| 26 | + { |
| 27 | + $translator = $this->getMock('SomeClass'); |
| 28 | + $translator->expects($this->any()) |
| 29 | + ->method('trans') |
| 30 | + ->willReturn('translated max {{ max }}!'); |
| 31 | + } |
| 32 | +} |
| 33 | +CODE_SAMPLE |
| 34 | + , |
| 35 | + <<<'CODE_SAMPLE' |
| 36 | +use PHPUnit\Framework\TestCase; |
| 37 | +
|
| 38 | +class SomeClass extends TestCase |
| 39 | +{ |
| 40 | + public function test() |
| 41 | + { |
| 42 | + $translator = $this->getMock('SomeClass'); |
| 43 | + $translator->method('trans') |
| 44 | + ->willReturn('translated max {{ max }}!'); |
| 45 | + } |
| 46 | +} |
| 47 | +CODE_SAMPLE |
| 48 | + ), |
| 49 | + ]); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * @return string[] |
| 54 | + */ |
| 55 | + public function getNodeTypes(): array |
| 56 | + { |
| 57 | + return [MethodCall::class]; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * @param MethodCall $node |
| 62 | + */ |
| 63 | + public function refactor(Node $node): ?Node |
| 64 | + { |
| 65 | + if (! $this->isInTestClass($node)) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + |
| 69 | + if (! $this->isName($node, 'expects')) { |
| 70 | + return null; |
| 71 | + } |
| 72 | + |
| 73 | + if (count($node->args) !== 1) { |
| 74 | + return null; |
| 75 | + } |
| 76 | + |
| 77 | + $onlyArgument = $node->args[0]->value; |
| 78 | + |
| 79 | + // @todo add match sequence method, ref https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/be664e0c9f3cca94d0bbefa06a731848144e4a22/src/Tokenizer/Tokens.php#L776 |
| 80 | + if (! $onlyArgument instanceof Node\Expr\MethodCall) { |
| 81 | + return null; |
| 82 | + } |
| 83 | + |
| 84 | + if (! $this->isName($onlyArgument->var, 'this')) { |
| 85 | + return null; |
| 86 | + } |
| 87 | + |
| 88 | + if (! $this->isName($onlyArgument, 'any')) { |
| 89 | + return null; |
| 90 | + } |
| 91 | + |
| 92 | + return $node->var; |
| 93 | + } |
| 94 | +} |
0 commit comments