Skip to content

round(): Validate the rounding mode #12252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 22, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
11 changes: 11 additions & 0 deletions ext/standard/math.c
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,17 @@ PHP_FUNCTION(round)
}
}

switch (mode) {
case PHP_ROUND_HALF_UP:
case PHP_ROUND_HALF_DOWN:
case PHP_ROUND_HALF_EVEN:
case PHP_ROUND_HALF_ODD:
break;
default:
zend_argument_value_error(3, "must be a valid rounding mode (PHP_ROUND_*)");
RETURN_THROWS();
}

Comment on lines +338 to +348
Copy link
Member Author

Choose a reason for hiding this comment

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

Previously an invalid rounding mode was considered to be equal to PHP_ROUND_HALF_UP. This is no longer the case since #12220. Making this a ValueError would be correct, but possibly a little steep. Shall I update this to a E_WARNING + change mode to PHP_ROUND_HALF_UP within the switch()? I don't want to update the rounding helper to handle unknown cases to keep the function clean.

Copy link
Member

Choose a reason for hiding this comment

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

I think having it directly a ValueError is fine IMHO, just add an entry in UPGRADING

switch (Z_TYPE_P(value)) {
case IS_LONG:
/* Simple case - long that doesn't need to be rounded. */
Expand Down
12 changes: 12 additions & 0 deletions ext/standard/tests/math/round_valid_rounding_mode.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
--TEST--
round() rejects invalid rounding modes.
--FILE--
<?php
var_dump(round(1.5, mode: 1234));
?>
--EXPECTF--
Fatal error: Uncaught ValueError: round(): Argument #3 ($mode) must be a valid rounding mode (PHP_ROUND_*) in %s:%d
Stack trace:
#0 %s(%d): round(1.5, 0, 1234)
#1 {main}
thrown in %s on line %d