Repository navigation
Implement assertGreaterThanOrEqual() and assertLessThanOrEqual() type narrowing - #359
Conversation
| /** | ||
| * @param 1|5|9.5 $a | ||
| * @param 1.5|5|9 $c | ||
| */ | ||
| public function integersAndFloatsOrEqual($a, $c): void | ||
| { | ||
| self::assertGreaterThanOrEqual(5.0, $a); | ||
| assertType('5|9.5', $a); | ||
|
|
||
| self::assertLessThanOrEqual(5.0, $c); | ||
| assertType('1.5|5', $c); | ||
| } |
There was a problem hiding this comment.
since we support float we should also test with INF and NAN
There was a problem hiding this comment.
Added tests in 00749f3: INF and -INF against int and 1.5|5, and NAN against int ranges, each as expected and as actual. Float parameters and plain int against NAN are left out, since PHPStan 2.3.0 and 2.3.7 infer different types for the first and both infer a type that is too wide for the second. PHPUnit 9.6 and 10.5 treat INF and -INF as equal, so assertGreaterThanOrEqual(INF, $float) passes for -INF while PHPStan 2.3.7 narrows $float to INF. Should the guard skip narrowing when both sides can be infinite?
| ), | ||
| 'GreaterThanOrEqual' => static function (Scope $scope, Arg $expected, Arg $actual): ?Expr\BinaryOp\GreaterOrEqual { | ||
| if (!self::isIntOrFloat($scope, $expected) || !self::isIntOrFloat($scope, $actual)) { | ||
| return null; |
There was a problem hiding this comment.
needs a test with values different from int|float
There was a problem hiding this comment.
Added notNarrowedActualTypesOrEqual (string, numeric string, array, object and mixed) and notNarrowedExpectedTypesOrEqual (array and mixed) in 00749f3. A nullable int as actual and '5' as expected were already covered by notNarrowedActualOrEqual and notNarrowedExpectedOrEqual.
|
Thank you! |
Closes #350
#351 left out the
*OrEqualvariants because PHPUnit checks equality with its own comparator. As proposed in #350 (comment), this narrows only when both arguments are int or float. With any other type on either side (numeric strings, nullable,mixed, arrays, objects) nothing is narrowed.One difference remains: where PHPUnit's comparator treats
INFand-INFas equal (seen on 9.6.39 and 10.5.67),assertGreaterThanOrEqual(INF, -INF)andassertLessThanOrEqual(-INF, INF)pass but are reported as always false.