phpstan / phpstan-strict-rules

Extra strict and opinionated rules for PHPStan
MIT License
604 stars 48 forks source link

Disallow casting potential nulls to int/string/array #224

Open leongersen opened 1 year ago

leongersen commented 1 year ago

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!

ondrejmirtes commented 1 year ago

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