phpstan-strict-rules icon indicating copy to clipboard operation
phpstan-strict-rules copied to clipboard

Disallow casting potential nulls to int/string/array

Open leongersen opened this issue 1 year ago • 1 comments

Feature request

I sometimes see PR's in my organisation where a cast to (int) is used to silence a PhpStan error about cases where int|null is passed somewhere that only allows int. This has resulted in bugs where inadvertent 0 values end up getting passed.

I've written a simple custom rule for Expr\Cast to check that the type of the cast expression is not "maybe a supertype of null". This results in helpful errors that can be used to improve some iffy code.

I'd say this rule would be a good addition to either one of the higher levels, or to phpstan-strict-rules. Would you be interested in such a rule?

The messaging could be something along the lines of casting should not be used to narrow types or casting to (int) should not be used to remove null from int|null.

Did PHPStan help you today? Did it make you happy in any way?

Yes! I've also found the processes used to build PhpStan hugely inspirational in improving my own engineering practises, so thank you!

leongersen avatar Aug 02 '23 12:08 leongersen

Yes, this is actually a good idea for phpstan-strict-rules 😊

ondrejmirtes avatar Aug 02 '23 13:08 ondrejmirtes