Skip to content

[TypeDeclaration] Skip redundant intersection types in union return types - #8527

Merged
TomasVotruba merged 2 commits into
rectorphp:mainfrom
kevin9327:fix-redundant-dnf-intersection
Oct 5, 2026
Merged

TomasVotruba merged 2 commits into
rectorphp:mainfrom
kevin9327:fix-redundant-dnf-intersection

Conversation

@kevin9327

Copy link
Copy Markdown
Contributor

ReturnUnionTypeRector can add a return type that PHP won't compile. If a value narrowed by instanceof is returned on one branch and the un-narrowed value on another, the inferred union contains both A and A&B, and both get printed:

public function run(\Iterator $obj)
{
    if (! $obj instanceof \Countable) {
        return $obj;
    }

    if (rand(0, 1)) {
        return $obj;
    }

    return '10';
}

becomes

public function run(\Iterator $obj): \Iterator|(\Countable&\Iterator)|string

and loading the file fails with:

PHP Fatal error:  Type Countable&Iterator is redundant as it is more restrictive than type Iterator

I found this by running Rector, with the PHP 8.4 set and the prepared sets, over laravel/framework, composer, guzzle, doctrine/orm and symfony/console, then running php -l on every changed file. It was the only file that stopped compiling: Illuminate\Log\LogManager::prepareHandler() got HandlerInterface|FingersCrossedHandler|(HandlerInterface&FormattableHandlerInterface)|(FingersCrossedHandler&FormattableHandlerInterface).

UnionTypeMapper::matchPhpParserUnionType() now drops any intersection member that contains every part of another member, whether that member is a single class or a smaller intersection. This is the same name-based check PHP runs at compile time. In the example above the result is \Iterator|string.

The new fixture FixtureUnionIntersection/redundant_intersection.php.inc fails without the change. The full vendor/bin/phpunit suite passes, and ECS and PHPStan report nothing new for the changed file.

Comment thread src/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php Outdated
Comment thread src/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php Outdated

@samsonasik samsonasik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good

@TomasVotruba
TomasVotruba merged commit b4d80f4 into rectorphp:main Oct 5, 2026
50 checks passed
@TomasVotruba

Copy link
Copy Markdown
Member

Thanks

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.

3 participants