Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d2d350d
RoundFunctionReturnTypeExtension supports types with ConstantScalar
Aug 26, 2024
5b6cdac
fix RoundFunctionReturnTypeExtension
Aug 26, 2024
607719b
add tests
Aug 26, 2024
3b572ff
fix style
Aug 26, 2024
64c4ca7
add tests
Aug 26, 2024
54e3b01
fix
Aug 26, 2024
554c91e
refactor method
Aug 26, 2024
d0a2ff5
fix
Aug 26, 2024
138c672
fix
Aug 26, 2024
fa19d0e
fix : Return null directly for unsupported constant values
ShioPy0101 Sep 20, 2026
8f24d00
feat : Support RoundingMode in round constant evaluation
ShioPy0101 Sep 20, 2026
9e98ba5
test : Add RoundingMode constant evaluation tests
ShioPy0101 Sep 20, 2026
8088ed9
test : Test named RoundingMode argument
ShioPy0101 Sep 20, 2026
a5d46a6
test : Test RoundingMode union fallback
ShioPy0101 Sep 20, 2026
e20a253
refactor : round mode resolution
ShioPy0101 Sep 20, 2026
6502bc7
fix : coding style
ShioPy0101 Sep 20, 2026
4484897
feat : support constant numeric strings in non-strict mode
ShioPy0101 Sep 20, 2026
e34f023
fix : Cast numeric strings before constant evaluation
ShioPy0101 Sep 20, 2026
a6b95ae
test : numeric string constant evaluation
ShioPy0101 Sep 20, 2026
577dcc4
Fix coding style
ShioPy0101 Sep 20, 2026
a759e87
fix : round mode return type
ShioPy0101 Sep 20, 2026
92e8961
fix : narrow round mode return type
ShioPy0101 Sep 20, 2026
ae29831
fix : lint
ShioPy0101 Sep 20, 2026
5214d89
fix : keep round mode resolution compatible with PHP 7.4
ShioPy0101 Sep 20, 2026
dac9763
test : update PHP 7 numeric string tests
ShioPy0101 Sep 20, 2026
57d9187
fix : clarify RoundingMode fallback
ShioPy0101 Sep 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 138 additions & 3 deletions src/Type/Php/RoundFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

namespace PHPStan\Type\Php;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantFloatType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
Expand All @@ -18,9 +20,21 @@
use PHPStan\Type\NullType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use function ceil;
use function count;
use function floor;
use function in_array;
use function is_float;
use function is_int;
use function is_numeric;
use function is_string;
use function round;
use const PHP_ROUND_HALF_DOWN;
use const PHP_ROUND_HALF_EVEN;
use const PHP_ROUND_HALF_ODD;
use const PHP_ROUND_HALF_UP;

#[AutowiredService]
final class RoundFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
Expand All @@ -47,7 +61,9 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,

$hasStricterRoundFunctions = $scope->getPhpVersion()->hasStricterRoundFunctions();

if (count($functionCall->getArgs()) < 1) {
$args = $functionCall->getArgs();

if (count($args) < 1) {
// PHP 8 fatals with a missing parameter, PHP 7 returns null.
if ($hasStricterRoundFunctions->yes()) {
return new NeverType(true);
Expand All @@ -56,12 +72,17 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
return new NullType();
}

$firstArgType = $scope->getType($functionCall->getArgs()[0]->value);

$firstArgType = $scope->getType($args[0]->value);
if ($firstArgType instanceof MixedType) {
return $defaultReturnType;
}

$functionName = $functionReflection->getName();
$returnConstantType = $this->resolveConstantType($functionName, $args, $scope, $firstArgType);
if ($returnConstantType !== null) {
return $returnConstantType;
}

if ($hasStricterRoundFunctions->yes()) {
if (!$scope->isDeclareStrictTypes()) {
$allowed = new UnionType([
Expand Down Expand Up @@ -93,4 +114,118 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
return new FloatType();
}

/**
* @return 1|2|3|4|null
*
* Returns null for RoundingMode cases without a corresponding
* PHP_ROUND_HALF_* constant, so constant evaluation falls back
* to the existing return-type logic.
*/
private function resolveRoundMode(Type $modeType): ?int
{
$mode = $modeType->getConstantScalarValues();

if (count($mode) === 1 && in_array($mode[0], [
PHP_ROUND_HALF_UP,
PHP_ROUND_HALF_DOWN,
PHP_ROUND_HALF_EVEN,
PHP_ROUND_HALF_ODD,
], true)) {
return $mode[0];
}

$enumCase = $modeType->getEnumCaseObject();

if ($enumCase === null || $enumCase->getClassName() !== 'RoundingMode') {
return null;
}

switch ($enumCase->getEnumCaseName()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this mapping ?

This loose some case.

assertType('float', round(9.5, 0, \RoundingMode::TowardsZero));
	assertType('float', round(9.5, 0, \RoundingMode::AwayFromZero));
	assertType('float', round(9.5, 0, \RoundingMode::NegativeInfinity));
	assertType('float', round(9.5, 0, \RoundingMode::PositiveInfinity));

You could keep the original value when the Enum exists no ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I intentionally limited the mapping to the four RoundingMode cases that have direct equivalents in the legacy PHP_ROUND_HALF_* constants. The intent was to avoid making constant evaluation depend on the runtime availability of the RoundingMode enum.

For the remaining cases, I currently fall back to the existing return-type logic because they do not have a direct legacy constant mapping.

That said, I agree that this is an implementation limitation rather than a limitation of RoundingMode itself. Preserving the enum case internally would allow all cases to be evaluated more precisely, so I think that would be a better direction.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am still considering the best approach here. The README states that PHPStan's source code is developed on PHP 8.2, while the distributed package and PHAR are transformed to run on PHP 7.2 and higher. Given that, I would prefer to avoid making constant evaluation depend on the runtime availability of RoundingMode.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any suggestion @staabm ?

case 'HalfAwayFromZero':
return PHP_ROUND_HALF_UP;
case 'HalfTowardsZero':
return PHP_ROUND_HALF_DOWN;
case 'HalfEven':
return PHP_ROUND_HALF_EVEN;
case 'HalfOdd':
return PHP_ROUND_HALF_ODD;
default:
return null;
}
}

/**
* @param Arg[] $args
*/
public function resolveConstantType(string $functionName, array $args, Scope $scope, Type $argType): ?Type
{
$proc = null;

if ($functionName === 'floor') {
$proc = static fn ($name) => floor($name);
} elseif ($functionName === 'ceil') {
$proc = static fn ($name) => ceil($name);
} elseif ($functionName === 'round') {
if (count($args) === 1) {
$proc = static fn ($name) => round($name);
} else {
if (isset($args[1]->value)) {
$precisionArg = $args[1]->value;
$precisionType = $scope->getType($precisionArg);
$precisions = $precisionType->getConstantScalarValues();
if (count($precisions) !== 1 || !is_int($precisions[0])) {
return null;
}
$precision = $precisions[0];
} else {
$precision = 0;
}

if (!isset($args[2]->value)) {
$proc = static fn ($name) => round($name, $precision);
} else {
$modeType = $scope->getType($args[2]->value);
$mode = $this->resolveRoundMode($modeType);

if ($mode === null) {
return null;
}

$proc = static fn ($name) => round($name, $precision, $mode);
}
}
}

if ($proc === null) {
return null;
}

$constantScalarValues = $argType->getConstantScalarValues();
$returnValueTypes = [];

foreach ($constantScalarValues as $constantScalarValue) {
if (is_int($constantScalarValue) || is_float($constantScalarValue)) {
$returnValueTypes[] = new ConstantFloatType($proc($constantScalarValue));
continue;
}

if (
!$scope->isDeclareStrictTypes()
&& is_string($constantScalarValue)
&& is_numeric($constantScalarValue)
) {
$returnValueTypes[] = new ConstantFloatType($proc((float) $constantScalarValue));
continue;
}

return null;
}

if (count($returnValueTypes) >= 1) {
return TypeCombinator::union(...$returnValueTypes);
}

return null;
}

}
96 changes: 90 additions & 6 deletions tests/PHPStan/Analyser/nsrt/round-php8-strict-types.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
}

// Round
assertType('float', round(123));
assertType('float', round(123.456));
assertType('123.0', round(123));
assertType('123.0', round(123.456));
assertType('float', round($_GET['foo'] / 60));
assertType('*NEVER*', round('123'));
assertType('*NEVER*', round('123.456'));
Expand All @@ -29,8 +29,8 @@
assertType('float', round($_GET['foo']));

// Ceil
assertType('float', ceil(123));
assertType('float', ceil(123.456));
assertType('123.0', ceil(123));
assertType('124.0', ceil(123.456));
assertType('float', ceil($_GET['foo'] / 60));
assertType('*NEVER*', ceil('123'));
assertType('*NEVER*', ceil('123.456'));
Expand All @@ -46,8 +46,8 @@
assertType('float', ceil($_GET['foo']));

// Floor
assertType('float', floor(123));
assertType('float', floor(123.456));
assertType('123.0', floor(123));
assertType('123.0', floor(123.456));
assertType('float', floor($_GET['foo'] / 60));
assertType('*NEVER*', floor('123'));
assertType('*NEVER*', floor('123.456'));
Expand All @@ -61,3 +61,87 @@
assertType('*NEVER*', floor(array(123)));
assertType('*NEVER*', floor());
assertType('float', floor($_GET['foo']));

/**
* @param 1.11|2.22 $floatUnionA
* @param 1.5|2.5 $floatUnionB
* @param 1.1|2.2|5.5|6.6 $floatUnionC
*/
function constant(float $floatUnionA, float $floatUnionB, float $floatUnionC)
{
assertType('3.0', round(3.4));
assertType('4.0', round(3.5));
assertType('4.0', round(3.6));
assertType('4.0', round(3.6, 0));
assertType('5.05', round(5.045, 2));
assertType('5.06', round(5.055, 2));
assertType('300.0', round(345, -2));
assertType('0.0', round(345, -3));
assertType('700.0', round(678, -2));
assertType('1000.0', round(678, -3));

assertType('1.1|2.2', round($floatUnionA, 1));
assertType('1.1|2.2', round($floatUnionA, 1, PHP_ROUND_HALF_UP));
assertType('1.0|2.0', round($floatUnionA, mode: PHP_ROUND_HALF_UP));
assertType('2.0|3.0', round($floatUnionB, mode: PHP_ROUND_HALF_UP));
assertType('1.0|2.0', round($floatUnionB, mode: PHP_ROUND_HALF_DOWN));
assertType('1.0|2.0|5.0|6.0', floor($floatUnionC));

$number = 135.79;
assertType('135.79', round($number, 3));
assertType('135.79', round($number, 2));
assertType('135.8', round($number, 1));
assertType('136.0', round($number, 0));
assertType('140.0', round($number, -1));
assertType('100.0', round($number, -2));
assertType('0.0', round($number, -3));

// Rounding modes with 9.5
assertType('10.0', round(9.5, 0, PHP_ROUND_HALF_UP));
assertType('9.0', round(9.5, 0, PHP_ROUND_HALF_DOWN));
assertType('10.0', round(9.5, 0, PHP_ROUND_HALF_EVEN));
assertType('9.0', round(9.5, 0, PHP_ROUND_HALF_ODD));

// Rounding modes with 8.5
assertType('9.0', round(8.5, 0, PHP_ROUND_HALF_UP));
assertType('8.0', round(8.5, 0, PHP_ROUND_HALF_DOWN));
assertType('8.0', round(8.5, 0, PHP_ROUND_HALF_EVEN));
assertType('9.0', round(8.5, 0, PHP_ROUND_HALF_ODD));

// Using PHP_ROUND_HALF_UP with 1 decimal digit precision
assertType('1.6', round( 1.55, 1, PHP_ROUND_HALF_UP));
assertType('-1.6', round(-1.55, 1, PHP_ROUND_HALF_UP));

// Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
assertType('1.5', round( 1.55, 1, PHP_ROUND_HALF_DOWN));
assertType('-1.5', round(-1.55, 1, PHP_ROUND_HALF_DOWN));

// Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
assertType('1.6', round( 1.55, 1, PHP_ROUND_HALF_EVEN));
assertType('-1.6', round(-1.55, 1, PHP_ROUND_HALF_EVEN));

// Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
assertType('1.5', round( 1.55, 1, PHP_ROUND_HALF_ODD));
assertType('-1.5', round(-1.55, 1, PHP_ROUND_HALF_ODD));
}

/**
* @param 1.11|2.22 $floatUnion
* @param 2|3 $precisionUnion
* @param 2|4 $modeUnion
* @param 1|'2.5' $IntOrNumStr
* @param 1.11|'2.22' $floatOrNumStr
*/
function notConstant(float $floatUnion, float $precisionUnion, float $modeUnion, $IntOrNumStr, $floatOrNumStr)
{
assertType('float', round($floatUnion, $precisionUnion, PHP_ROUND_HALF_UP));
assertType('float', round($floatUnion, 0, $modeUnion));

assertType('float', round($IntOrNumStr));
assertType('float', round($IntOrNumStr, mode: PHP_ROUND_HALF_UP));
assertType('float', round($IntOrNumStr, mode: PHP_ROUND_HALF_DOWN));

assertType('float', round($floatOrNumStr));
assertType('float', round($floatOrNumStr, mode: PHP_ROUND_HALF_UP));
assertType('float', round($floatOrNumStr, mode: PHP_ROUND_HALF_DOWN));
}
Loading
Loading