diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithTwoOrMoreCount.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithTwoOrMoreCount.php.inc deleted file mode 100644 index 685c7f67..00000000 --- a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithTwoOrMoreCount.php.inc +++ /dev/null @@ -1,33 +0,0 @@ -expects($this->at(2)) - ->method('foo') - ->willReturn('1'); - } -} -?> ------ -expects($this->exactly(2)) - ->method('foo') - ->willReturn('1'); - } -} -?> diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithZeroCount.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithZeroCount.php.inc deleted file mode 100644 index d585c6d2..00000000 --- a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithZeroCount.php.inc +++ /dev/null @@ -1,33 +0,0 @@ -expects($this->at(0)) - ->method('foo') - ->willReturn('1'); - } -} -?> ------ -expects($this->never()) - ->method('foo') - ->willReturn('1'); - } -} -?> diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/MultipleAtWithDifferentCount.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/MultipleAtWithDifferentCount.php.inc deleted file mode 100644 index 84fde23e..00000000 --- a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/MultipleAtWithDifferentCount.php.inc +++ /dev/null @@ -1,55 +0,0 @@ -expects($this->at(0)) - ->method('foo') - ->willReturn('1'); - - $mock->expects($this->at(1)) - ->method('foo') - ->willReturn('1'); - - $mock->expects($this->at(2)) - ->method('foo') - ->willReturn('1'); - $mock->expects($this->at(3)) - ->method('foo') - ->willReturn('1'); - } -} -?> ------ -expects($this->never()) - ->method('foo') - ->willReturn('1'); - - $mock->expects($this->once()) - ->method('foo') - ->willReturn('1'); - - $mock->expects($this->exactly(2)) - ->method('foo') - ->willReturn('1'); - $mock->expects($this->exactly(3)) - ->method('foo') - ->willReturn('1'); - } -} -?> diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/consecutive_calls.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/consecutive_calls.php.inc new file mode 100644 index 00000000..14be03cf --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/consecutive_calls.php.inc @@ -0,0 +1,46 @@ +createMock(\stdClass::class); + $mock->expects($this->at(0)) + ->method('foo') + ->with(1) + ->willReturn('a'); + + $mock->expects($this->at(1)) + ->method('foo') + ->with(2) + ->willReturn('b'); + + $mock->expects(self::at(2)) + ->method('foo') + ->with(3) + ->willReturn('c'); + } +} + +?> +----- +createMock(\stdClass::class); + $mock->expects($this->exactly(3))->method('foo')->withConsecutive([1], [2], [3])->willReturnOnConsecutiveCalls('a', 'b', 'c'); + } +} + +?> diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithOneCount.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/lone_at_zero.php.inc similarity index 70% rename from rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithOneCount.php.inc rename to rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/lone_at_zero.php.inc index 048f0ce3..411be31e 100644 --- a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/AtWithOneCount.php.inc +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/lone_at_zero.php.inc @@ -4,15 +4,17 @@ namespace Rector\PHPUnit\Tests\PHPUnit90\Rector\MethodCall\ReplaceAtMethodWithDe use PHPUnit\Framework\TestCase; -final class AtWithOneCountTest extends TestCase +final class LoneAtZeroTest extends TestCase { public function test() { - $mock->expects($this->at(1)) + $mock = $this->createMock(\stdClass::class); + $mock->expects($this->at(0)) ->method('foo') ->willReturn('1'); } } + ?> ----- createMock(\stdClass::class); $mock->expects($this->once()) ->method('foo') ->willReturn('1'); } } + ?> diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_different_methods.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_different_methods.php.inc new file mode 100644 index 00000000..4a2d8b8f --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_different_methods.php.inc @@ -0,0 +1,15 @@ +createMock(\stdClass::class); + $mock->expects($this->at(0))->method('foo')->willReturn('1'); + $mock->expects($this->at(1))->method('bar')->willReturn('2'); + } +} diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_index_gap.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_index_gap.php.inc new file mode 100644 index 00000000..fb530d13 --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_index_gap.php.inc @@ -0,0 +1,14 @@ +createMock(\stdClass::class); + $mock->expects($this->at(1))->method('foo')->willReturn('1'); + } +} diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_other_expectation.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_other_expectation.php.inc new file mode 100644 index 00000000..0e1c28c1 --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_other_expectation.php.inc @@ -0,0 +1,15 @@ +createMock(\stdClass::class); + $mock->expects($this->at(0))->method('foo')->willReturn('1'); + $mock->expects($this->once())->method('bar'); + } +} diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_partial_with.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_partial_with.php.inc new file mode 100644 index 00000000..316f80df --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_partial_with.php.inc @@ -0,0 +1,15 @@ +createMock(\stdClass::class); + $mock->expects($this->at(0))->method('foo')->with(1); + $mock->expects($this->at(1))->method('foo'); + } +} diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_property_mock.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_property_mock.php.inc new file mode 100644 index 00000000..eba79462 --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_property_mock.php.inc @@ -0,0 +1,14 @@ +createMock(\stdClass::class); + $this->mock->expects($this->at(0))->method('foo')->willReturn('1'); + } +} diff --git a/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_stubbed_call.php.inc b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_stubbed_call.php.inc new file mode 100644 index 00000000..b910fad8 --- /dev/null +++ b/rules-tests/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector/Fixture/skip_stubbed_call.php.inc @@ -0,0 +1,15 @@ +createMock(\stdClass::class); + $mock->method('bar')->willReturn('2'); + $mock->expects($this->at(0))->method('foo')->willReturn('1'); + } +} diff --git a/rules/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector.php b/rules/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector.php index f6ad541a..b18d83ba 100644 --- a/rules/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector.php +++ b/rules/PHPUnit90/Rector/MethodCall/ReplaceAtMethodWithDesiredMatcherRector.php @@ -6,14 +6,26 @@ use PhpParser\Node; use PhpParser\Node\Arg; +use PhpParser\Node\Expr; +use PhpParser\Node\Expr\Array_; +use PhpParser\Node\Expr\ArrayItem; use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Identifier; use PhpParser\Node\Scalar\Int_; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\Node\Stmt\Expression; use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer; use Rector\Rector\AbstractRector; use Rector\RuleDoc\CodeSample\CodeSample; use Rector\RuleDoc\RuleDefinition; /** + * at($index) matches the call at that position among all calls on the mock, so all at() expectations of one mock + * are rewritten together, or not at all. + * * @see \Rector\PHPUnit\Tests\PHPUnit90\Rector\MethodCall\ReplaceAtMethodWithDesiredMatcherRector\ReplaceAtMethodWithDesiredMatcherRectorTest */ final class ReplaceAtMethodWithDesiredMatcherRector extends AbstractRector @@ -26,19 +38,23 @@ public function __construct( public function getRuleDefinition(): RuleDefinition { return new RuleDefinition( - 'Replace at() method call with desired matcher', + 'Replace at() method calls of one mock with a single matcher, when they expect consecutive calls of the same method', [ new CodeSample( <<<'CODE_SAMPLE' $mock->expects($this->at(0)) ->method('foo') - ->willReturn('1'); + ->with(1) + ->willReturn('a'); + +$mock->expects($this->at(1)) + ->method('foo') + ->with(2) + ->willReturn('b'); CODE_SAMPLE , <<<'CODE_SAMPLE' -$mock->expects($this->never()) - ->method('foo') - ->willReturn('1'); +$mock->expects($this->exactly(2))->method('foo')->withConsecutive([1], [2])->willReturnOnConsecutiveCalls('a', 'b'); CODE_SAMPLE ), ] @@ -50,73 +66,289 @@ public function getRuleDefinition(): RuleDefinition */ public function getNodeTypes(): array { - return [MethodCall::class]; + return [ClassMethod::class]; } /** - * @param MethodCall $node + * @param ClassMethod $node */ - public function refactor(Node $node): null|MethodCall + public function refactor(Node $node): ?ClassMethod { - if (! $this->testsNodeAnalyzer->isInTestClass($node)) { + if ($node->stmts === null || ! $this->testsNodeAnalyzer->isInTestClass($node)) { return null; } - if (! $node->var instanceof MethodCall) { + /** @var array> $expectationsByMock */ + $expectationsByMock = []; + + // a stubbed method call shifts the at() indexes too + $stubbedMocks = []; + foreach ($node->stmts as $key => $stmt) { + if (! $stmt instanceof Expression || ! $stmt->expr instanceof MethodCall) { + continue; + } + + $expectsMethodCall = $this->findChainCall($stmt->expr, 'expects'); + if ($expectsMethodCall instanceof MethodCall) { + $mockName = $this->getName($expectsMethodCall->var); + if (! $expectsMethodCall->var instanceof Variable || $mockName === null) { + continue; + } + + $expectationsByMock[$mockName][$key] = $stmt; + continue; + } + + $methodMethodCall = $this->findChainCall($stmt->expr, 'method'); + if ($methodMethodCall instanceof MethodCall && $methodMethodCall->var instanceof Variable) { + $stubbedMocks[(string) $this->getName($methodMethodCall->var)] = true; + } + } + + $hasChanged = false; + foreach ($expectationsByMock as $mockName => $expectations) { + if (isset($stubbedMocks[$mockName])) { + continue; + } + + $sequence = $this->resolveSequence($expectations); + if ($sequence === null) { + continue; + } + + $firstKey = array_key_first($expectations); + if (count($sequence) === 1) { + $this->replaceAtWithOnce($sequence[0]); + $hasChanged = true; + continue; + } + + $node->stmts[$firstKey] = new Expression($this->createConsecutiveExpectation($sequence)); + foreach (array_keys($expectations) as $key) { + if ($key !== $firstKey) { + unset($node->stmts[$key]); + } + } + + $hasChanged = true; + } + + if (! $hasChanged) { return null; } - $arg = $this->findAtMethodCall($node->var); - if (! $arg instanceof Arg) { + $node->stmts = array_values($node->stmts); + return $node; + } + + private function findChainCall(MethodCall $methodCall, string $name): ?MethodCall + { + $current = $methodCall; + while ($current instanceof MethodCall) { + if ($this->isName($current->name, $name)) { + return $current; + } + + $current = $current->var; + } + + return null; + } + + /** + * Every expectation of the mock is at(), the indexes run 0..n-1 without a gap, all on the same method, with only + * with() and willReturn() besides, and either all or none of them using each. + * + * @param array $expectations + * @return array|null + */ + private function resolveSequence(array $expectations): ?array + { + $sequence = []; + foreach ($expectations as $expectation) { + /** @var MethodCall $methodCall */ + $methodCall = $expectation->expr; + + $parts = $this->resolveParts($methodCall); + if ($parts === null) { + return null; + } + + [$index, $part] = $parts; + if (isset($sequence[$index])) { + return null; + } + + $sequence[$index] = $part; + } + + ksort($sequence); + if (array_keys($sequence) !== range(0, count($sequence) - 1)) { + return null; + } + + $methodName = $sequence[0]['method']->value; + $withCount = 0; + $willReturnCount = 0; + foreach ($sequence as $part) { + if (strtolower($part['method']->value) !== strtolower($methodName)) { + return null; + } + + $withCount += $part['with'] === null ? 0 : 1; + $willReturnCount += $part['willReturn'] instanceof Arg ? 1 : 0; + } + + if (! in_array($withCount, [0, count($sequence)], true)) { return null; } - if (! $arg->value instanceof MethodCall) { + if (! in_array($willReturnCount, [0, count($sequence)], true)) { return null; } - $count = null; - foreach ($arg->value->getArgs() as $item) { - if ($item->value instanceof Int_) { - $count = $item->value->value; + return $sequence; + } + + /** + * @return array{int, array{expects: MethodCall, method: String_, with: Arg[]|null, willReturn: Arg|null}}|null + */ + private function resolveParts(MethodCall $methodCall): ?array + { + $method = null; + $with = null; + $willReturn = null; + + $current = $methodCall; + while ($current instanceof MethodCall && ! $this->isName($current->name, 'expects')) { + if ($current->isFirstClassCallable()) { + return null; + } + + $args = $current->getArgs(); + if ($this->isName($current->name, 'method') && ! $method instanceof String_ && count($args) === 1 && $args[0]->value instanceof String_) { + $method = $args[0]->value; + } elseif ($this->isName($current->name, 'with') && $with === null && $this->arePlainArgs($args)) { + $with = $args; + } elseif ($this->isName($current->name, 'willReturn') && ! $willReturn instanceof Arg && count($args) === 1 && $this->arePlainArgs($args)) { + $willReturn = $args[0]; + } else { + return null; } + + $current = $current->var; + } + + // a property mock may get more expectations in setUp() or another helper + if (! $current instanceof MethodCall || ! $current->var instanceof Variable || ! $method instanceof String_ || $current->isFirstClassCallable()) { + return null; } - if (! isset($count)) { + $expectsArgs = $current->getArgs(); + if (count($expectsArgs) !== 1) { return null; } - if ($count === 0) { - $arg->value = new MethodCall($arg->value->var, 'never'); - return $node; + $index = $this->resolveAtIndex($expectsArgs[0]->value); + if ($index === null) { + return null; } - if ($count === 1) { - $arg->value = new MethodCall($arg->value->var, 'once'); - return $node; + return [$index, [ + 'expects' => $current, + 'method' => $method, + 'with' => $with, + 'willReturn' => $willReturn, + ]]; + } + + private function resolveAtIndex(Expr $expr): ?int + { + if ($expr instanceof MethodCall) { + if (! $expr->var instanceof Variable || ! $this->isName($expr->var, 'this')) { + return null; + } + } elseif ($expr instanceof StaticCall) { + if (! $this->isNames($expr->class, ['self', 'static'])) { + return null; + } + } else { + return null; } - if ($count > 1) { - $arg->value = new MethodCall($arg->value->var, 'exactly', [new Arg(new Int_($count))]); - return $node; + if (! $this->isName($expr->name, 'at') || $expr->isFirstClassCallable()) { + return null; } - return null; + $args = $expr->getArgs(); + if (count($args) !== 1 || ! $args[0]->value instanceof Int_) { + return null; + } + + return $args[0]->value->value; + } + + /** + * @param Arg[] $args + */ + private function arePlainArgs(array $args): bool + { + return array_all($args, fn (Arg $arg): bool => ! $arg->unpack && ! $arg->name instanceof Identifier); } - private function findAtMethodCall(MethodCall $methodCall): ?Arg + /** + * @param array{expects: MethodCall, method: String_, with: Arg[]|null, willReturn: Arg|null} $part + */ + private function replaceAtWithOnce(array $part): void { - foreach ($methodCall->getArgs() as $arg) { - $argExpr = $arg->value; - if ($argExpr instanceof MethodCall && $this->isName($argExpr->name, 'at')) { - return $arg; + $atCall = $part['expects']->getArgs()[0]->value; + if ($atCall instanceof MethodCall) { + $part['expects']->args[0] = new Arg(new MethodCall($atCall->var, 'once')); + return; + } + + /** @var StaticCall $atCall */ + $part['expects']->args[0] = new Arg(new StaticCall($atCall->class, 'once')); + } + + /** + * @param array $sequence + */ + private function createConsecutiveExpectation(array $sequence): MethodCall + { + $first = $sequence[0]; + + /** @var MethodCall|StaticCall $atCall */ + $atCall = $first['expects']->getArgs()[0]->value; + $countArgs = [new Arg(new Int_(count($sequence)))]; + $exactly = $atCall instanceof MethodCall + ? new MethodCall($atCall->var, 'exactly', $countArgs) + : new StaticCall($atCall->class, 'exactly', $countArgs); + + $methodCall = new MethodCall($first['expects']->var, 'expects', [new Arg($exactly)]); + $methodCall = new MethodCall($methodCall, 'method', [new Arg($first['method'])]); + + if ($first['with'] !== null) { + $consecutiveArgs = []; + foreach ($sequence as $part) { + $items = array_map(static fn (Arg $arg): ArrayItem => new ArrayItem($arg->value), (array) $part['with']); + $consecutiveArgs[] = new Arg(new Array_($items)); } + + $methodCall = new MethodCall($methodCall, 'withConsecutive', $consecutiveArgs); } - if ($methodCall->var instanceof MethodCall) { - $this->findAtMethodCall($methodCall->var); + if ($first['willReturn'] instanceof Arg) { + $returnArgs = []; + foreach ($sequence as $part) { + /** @var Arg $willReturn */ + $willReturn = $part['willReturn']; + $returnArgs[] = new Arg($willReturn->value); + } + + $methodCall = new MethodCall($methodCall, 'willReturnOnConsecutiveCalls', $returnArgs); } - return null; + return $methodCall; } }