rector icon indicating copy to clipboard operation
rector copied to clipboard

ReturnTypeFromStrictScalarReturnExprRector adds invalid return type ?mixed

Open thomasschiet opened this issue 3 years ago • 2 comments

Bug Report

Subject Details
Rector version v0.14.0

When a function returns either null or mixed, the ReturnTypeFromStrictScalarReturnExprRector rule adds ?mixed. This causes a fatal error:

Type mixed cannot be marked as nullable since mixed already includes null  

Minimal PHP Code Causing Issue

Reproduction

<?php

function returnsNullOrMixed()
{
    if (rand() < 0.5) {
        return null;
    }

    return json_decode('something', null, 512, JSON_THROW_ON_ERROR);
}

Expected Behaviour

Should add mixed instead of ?mixed.

thomasschiet avatar Sep 21 '22 13:09 thomasschiet

@thomasschiet could you try provide a PR patch? You can do the following steps:

  1. Add failing fixture on

https://github.com/rectorphp/rector-src/tree/b54c62993056f984ca68d75c654b98794f931582/rules-tests/CodeQuality/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector/Fixture

  1. Run test:
vendor/bin/phpunit rules-tests/CodeQuality/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector
  1. Provide a patch, this seems bug on UnionTypeMapper, which mixed can't be included in NullableType at at https://github.com/rectorphp/rector-src/blob/b54c62993056f984ca68d75c654b98794f931582/packages/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php#L141
-        if (! $this->nodeNameResolver->isName($nullabledTypeNode, 'false')) {
+        if (! $this->nodeNameResolver->isNames($nullabledTypeNode, ['false', 'mixed'])) {

Thank you.

samsonasik avatar Sep 22 '22 08:09 samsonasik

@samsonasik Thanks! I'll provide the PR later today.

thomasschiet avatar Sep 22 '22 08:09 thomasschiet