Disallow casting potential nulls to int/string/array

Open
#224 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
30/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
php
Domain
devtools

Research direction

Start by reviewing PHPStan's Expr\Cast handling and the proposed custom rule for detecting nullable expressions cast to int, string, or array. Done means the selected rule level reports casts that remove a possible null value, with messaging that explains the narrowing, while safe casts remain accepted.

Written by the indexing model from the issue text.

Description

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!

Dominant language
PHP
Stars
709
Forks
62
Avg merge
5d 19h
Merged PRs (30d)
3

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from phpstan/phpstan-strict-rules

All issues in phpstan/phpstan-strict-rules

Similar issues

More PHP issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.