Skip to content

[CodeQuality] Add WillReturnCallbackFallbackToThrowRector#710

Merged
TomasVotruba merged 1 commit into
mainfrom
throw-on-consecutive-fallback
Jul 11, 2026
Merged

[CodeQuality] Add WillReturnCallbackFallbackToThrowRector#710
TomasVotruba merged 1 commit into
mainfrom
throw-on-consecutive-fallback

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Adds a rule that turns the unreachable fallback return of a consecutive willReturnCallback() into a throw, so an unexpected extra call fails loudly instead of silently returning a stale value.

After withConsecutive() is migrated to a matcher willReturnCallback(), the trailing return is a leftover of the original single willReturn() — it is reached only when the mock is called more often than expected. Returning there hides the over-call; throwing surfaces it.

 $this->someServiceMock->expects($matcher)
     ->method('run')
     ->willReturnCallback(function () use ($matcher) {
         if ($matcher->numberOfInvocations() === 1) {
             return 'first';
         }

         if ($matcher->numberOfInvocations() === 2) {
             return 'second';
         }

-        return 'second';
+        throw new \PHPUnit\Framework\Exception(sprintf('Method should not be called for the %dth time', $matcher->numberOfInvocations()));
     });

Only fires when the closure uses $matcher, branches on its invocation count, and ends with an unconditional return. Added to the phpunit-code-quality set.

@TomasVotruba TomasVotruba force-pushed the throw-on-consecutive-fallback branch 3 times, most recently from 573eecc to 563adae Compare July 11, 2026 16:42
@TomasVotruba TomasVotruba force-pushed the throw-on-consecutive-fallback branch from 242d59f to 85797b5 Compare July 11, 2026 16:43
@TomasVotruba TomasVotruba enabled auto-merge (squash) July 11, 2026 16:43
@TomasVotruba TomasVotruba merged commit 44c5166 into main Jul 11, 2026
8 checks passed
@TomasVotruba TomasVotruba deleted the throw-on-consecutive-fallback branch July 11, 2026 16:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant