Skip to content

Report NAN and INF reaching conversions, json_encode() and formatting - #7086

Open
zonuexe wants to merge 1 commit into
phpstan:2.3.xfrom
zonuexe:non-finite-float-rules
Open

zonuexe wants to merge 1 commit into
phpstan:2.3.xfrom
zonuexe:non-finite-float-rules

Conversation

@zonuexe

@zonuexe zonuexe commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

This PR adds rules that report a float that may be NAN, INF or -INF reaching code that does not handle it, as proposed in phpstan/phpstan#15751. The issue has the runtime behaviour (https://3v4l.org/TPOsd) and the open points.

Tiers

  • The rules are registered with a new feature toggle, nonFiniteFloats, on in bleedingEdge. They report a value that is certainly non-finite, like NAN, INF, a float narrowed by is_nan(), or an array shape with such a value in a key that is not optional.
  • The new parameter checkNonFiniteFloats (off by default) also reports a value that may be non-finite, which includes plain float.
  • mixed is not reported.

Rules

Identifier Rules Reports PHP versions
nonFiniteFloat.jsonEncode JsonEncodeNonFiniteFloatRule the value of json_encode() and the values of arrays in it all
nonFiniteFloat.toString EchoNanRule, PrintNanRule, ConcatNanRule, AssignConcatNanRule, InterpolatedStringNanRule, StringCastNanRule NAN converted to string 8.5+
nonFiniteFloat.toInt IntCastNonFiniteFloatRule, IntvalNonFiniteFloatRule NAN, INF and floats out of the int range in (int) and intval() 8.5+
nonFiniteFloat.format FormatNonFiniteFloatRule number_format(), and the float, int and %s placeholders of printf(), sprintf() and fprintf() all (%s: 8.5+)
  • NonFiniteFloatHelper decides for each rule whether the float part of a value can be one of the floats it does not handle, and whether to report it.
  • PhpVersion::warnsOnNonFiniteFloatConversion() and PhpVersions::warnsOnNonFiniteFloatConversion() gate the PHP 8.5 warnings.

Testing

  • NonFiniteFloatRulesTest runs every rule on one file: once without checkNonFiniteFloats and once with it. The conversions to string and int are expected only on PHP 8.5+.
  • NonFiniteFloatRulesPhp84Test runs the same file with phpVersion: 80400 and expects none of them.
  • On phpstan-src itself, at level 8 with bleedingEdge and phpVersion: 80500, the bleedingEdge tier reports nothing, and checkNonFiniteFloats reports 46 places.

The documentation of checkNonFiniteFloats on phpstan.org would follow once the design is settled.

Closes phpstan/phpstan#15751

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Report NAN and INF reaching conversions, json_encode() and formatting

1 participant