php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Numeric casts could emit a warning it they do not make sense

Open mvorisek opened this issue 4 years ago • 4 comments

Description

(float) '1';
(float) '1.0';
(float) '';
(float) 'x'; // should always warn

(int) '1';
(int) '1.0';
(int) '';
(int) 'x'; // should always warn

https://3v4l.org/gDLOv

This is a feature request. The casts above are advised by many static analysers, but if added explicitly, there is currently no warning emit. They should at least emit a warning if the input is not numerical and the cast does not make sense.

mvorisek avatar Apr 03 '22 11:04 mvorisek

As designed, casts just enforce type conversion; it's basically the programmer saying "I'm a big boy, I know what I'm doing". Changing that long-standing behavior would require the RFC process.

cmb69 avatar Apr 04 '22 10:04 cmb69

FWIW we at least have some warnings already when casting to strings.

https://3v4l.org/UsMnb

var_dump((string) []);

Warning: Array to string conversion in /in/UsMnb on line 3 string(5) "Array"

I do think casting a non-numeric string to ints is often indicative of an error. Either way, as Christoph mentioned, this would require an RFC.

iluuu1994 avatar Apr 04 '22 12:04 iluuu1994

While we warn when casting an array to a string, this is about preventing the whole class of arrays, and not specific patterns of arrays (like with strings where numerical ones would be allowed).

To get a checked cast of a string to a number, I'd recommend the one-char variant, prepending a + sign. Given that there is a short way to do a checked conversion to number (plus sign) - and a longer (the cast) unchecked version, I do not think there's a need for a change. In fact it's a good thing that there exists a (relatively easy) way to do unchecked casts "just squeeze that into a number". It's a safe way of doing that which existed since very old times and should stay. A common use case for int casts is taking (possibly client-side validated) user inputs for example. You do not really want to break this common scenario.

bwoebi avatar Apr 07 '22 10:04 bwoebi

his is about preventing the whole class of arrays, and not specific patterns of arrays

We also throw when casting non-stringable objects to strings, while stringable objects are obviously allowed.

"just squeeze that into a number". It's a safe way of doing that which existed since very old times and should stay.

Yeah, that's a valid concern. (int)$foo !== 0 is probably a common pattern when 0 is not a valid value.

iluuu1994 avatar Apr 07 '22 10:04 iluuu1994