Skip to content

[CodeQuality] Handle return throw and return null in void mock callbacks#713

Merged
TomasVotruba merged 1 commit into
mainfrom
fix/void-callback-return-throw
Jul 12, 2026
Merged

[CodeQuality] Handle return throw and return null in void mock callbacks#713
TomasVotruba merged 1 commit into
mainfrom
fix/void-callback-return-throw

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

When a mocked void method's willReturnCallback() closure mixes return null; with a return throw new X;, RemoveReturnFromVoidMethodMockCallbackRector bailed out (a return throw is not a "pure" value), so it stripped nothing and typed nothing. TypeWillReturnCallableArrowFunctionRector then added : void on its own, leaving the value returns in place — producing code that fatals:

PHP Fatal error: A void function must not return a value

Note return throw new X; is also illegal in a void function, so stripping only return null; is not enough — the return must be dropped from the throw too.

This makes the rule normalize the whole void closure instead of bailing:

  • return null; (and other pure returns) → return;
  • return throw new X;throw new X;
  • closure typed : void

Impure, non-throw value returns still bail safely (behavior unchanged).

Before → After

             ->method('persist')
-            ->willReturnCallback(function ($entity) use ($matcher) {
+            ->willReturnCallback(function ($entity) use ($matcher): void {
                 if (1 === $matcher->numberOfInvocations()) {
-                    return null;
+                    return;
                 }

                 if (2 === $matcher->numberOfInvocations()) {
-                    return throw new \RuntimeException('boom');
+                    throw new \RuntimeException('boom');
                 }
             });

@TomasVotruba TomasVotruba merged commit 749dc8b into main Jul 12, 2026
8 checks passed
@TomasVotruba TomasVotruba deleted the fix/void-callback-return-throw branch July 12, 2026 10:04
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