Skip to content

[TypeDeclaration] Add ClosureReturnTypeFromAssertInstanceOfRector#8115

Merged
TomasVotruba merged 1 commit into
mainfrom
tv-closure-return-type-in-testcase
Jun 29, 2026
Merged

[TypeDeclaration] Add ClosureReturnTypeFromAssertInstanceOfRector#8115
TomasVotruba merged 1 commit into
mainfrom
tv-closure-return-type-in-testcase

Conversation

@TomasVotruba

@TomasVotruba TomasVotruba commented Jun 29, 2026

Copy link
Copy Markdown
Member

Adds ClosureReturnTypeFromAssertInstanceOfRector — adds a return type to a closure inside a PHPUnit TestCase when the returned value is narrowed by assertInstanceOf().

This is the critical case ClosureReturnTypeRector cannot cover: the closure body asserts the type, so the return is known. Plain closures without assertInstanceOf() are left to ClosureReturnTypeRector.

use PHPUnit\Framework\TestCase;

final class SomeTest extends TestCase
{
    public function test()
    {
        // before
        $callback = function (object $object) {
            $this->assertInstanceOf(SomeType::class, $object);
            return $object;
        };

        // after
        $callback = function (object $object): SomeType {
            $this->assertInstanceOf(SomeType::class, $object);
            return $object;
        };
    }
}

Scope

  • Closure only (arrow functions cannot hold an assertInstanceOf() statement before the return)
  • Gated on enclosing class ->is('PHPUnit\Framework\TestCase')
  • Requires assertInstanceOf() ($this-> or static) in the closure body; skipped otherwise
  • Return type inferred via ReturnTypeInferer (PHPStan phpunit type-specifier narrows the asserted variable)
  • Registered in TypeDeclarationLevel

Fixtures: assertInstanceOf-narrowed return (transforms), no-assertInstanceOf (skip), outside test case (skip).

@TomasVotruba TomasVotruba force-pushed the tv-closure-return-type-in-testcase branch from 424bde0 to 556df17 Compare June 29, 2026 15:08
… assertInstanceOf-narrowed closure returns in test cases
@TomasVotruba TomasVotruba force-pushed the tv-closure-return-type-in-testcase branch from 556df17 to 21f5281 Compare June 29, 2026 15:49
@TomasVotruba TomasVotruba changed the title [TypeDeclaration] Add ClosureReturnTypeInTestCaseRector [TypeDeclaration] Add ClosureReturnTypeFromAssertInstanceOfRector Jun 29, 2026
@TomasVotruba TomasVotruba merged commit ef1594b into main Jun 29, 2026
65 checks passed
@TomasVotruba TomasVotruba deleted the tv-closure-return-type-in-testcase branch June 29, 2026 15:56
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