Phpinspectionsea: False Positive: `Unnecessary type casting` with null safe operator

Created on 13 Mar 2021  路  5Comments  路  Source: kalessil/phpinspectionsea


| Subject | Details |
| :------------- | :---------------------------------------------------------------------------- |
| Plugin | Php Inspections (EA Extended) or Php Inspections (EA Ultimate), 3.0.10 |
| Language level | PHP 8 |

Current behaviour

For the following code

<?php

class Foo {
    public function returnBool(): bool {
        return random_int(0,1) > 0;
    }
}

function returnsBool(?Foo $foo): bool {
    return (bool) $foo?->returnBool();
}

var_dump(returnsBool(null));

(bool) is highlighted as unnecessary type cast.

Expected behaviour

As it can be seen here, when there is no type cast, a TypeError is thrown.

Environment details

n/a

bug / false-positive fixed

Most helpful comment

@ktomk: the reported construct is fully valid, and following inspection suggestion will change behavior. Different projects have different coding standards, so the suggested alternative might not fit to what folks are doing on daily basis. We need to fix this on our end.

All 5 comments

How does the TypeError which is clearly intended in the code example by specifying the return type bool render the type casting necessary?

You either have the wrong return type or the return code is written "wrong". In both cases the cast is indeed unnecessary:

return $foo?->returnBool() ?? false;

you want to have null in the null safe operation as false - express it ;) - as it can be seen here.

Thanks for reporting @canvural, we are able to reproduce the bug. We are working on fixing it.

@ktomk: the reported construct is fully valid, and following inspection suggestion will change behavior. Different projects have different coding standards, so the suggested alternative might not fit to what folks are doing on daily basis. We need to fix this on our end.

@ea-inspections-team: I'm in for the tweak.

Fixed! The fix will be available in the next release.

Was this page helpful?
0 / 5 - 0 ratings