mistic100/RandomColor.php

Implicit conversion Exception in PHP8.1

nono303 opened this issue · 5 comments

Hi @mistic100,
Here is an exception thrown with php8.1 calling RandomColor::one(['hue'=>['blue','yellow','pink','purple','orange','red','green']])

Implicit conversion from float 87.6 to int loses precision - #0 [internal function]: {closure}()
#1 \composer\vendor\mistic100\randomcolor\src\RandomColor.php(263): mt_rand()
#2 \composer\vendor\mistic100\randomcolor\src\RandomColor.php(165): Colors\RandomColor::_rand()
#3 \composer\vendor\mistic100\randomcolor\src\RandomColor.php(44): Colors\RandomColor::_pickBrightness()

My quick patch, but might be fix higher in the call stack

diff --git "a/src/RandomColor.php" "b/src/RandomColor.php"
index df96204..f1ee99b 100644
--- "a/src/RandomColor.php"
+++ "b/src/RandomColor.php"
@@ -260,7 +260,7 @@ class RandomColor
     }
     else
     {
-      return mt_rand($bounds[0], $bounds[1]);
+      return mt_rand(round($bounds[0]), round($bounds[1]));
     }
   }
 

sounds legit, it might also be done while calling $options['prng']

can you do a PR ?

I don't understand what you mean by

but might be fix hugher in s=the call stack

might be fix higher in the call stack

...better with good letters at good place
I would like to say that fix might be done when generating $bounds not only when using it.

what about $options['prng'] as there is no call to mt_rand which require int?
you want a PR for the previous 1 line patch proposed ?

what about $options['prng'] as there is no call to mt_rand which require int?

The goal is the same, you don't know how the user might have implemented "prng", and the values should't be floats anyway

you want a PR for the previous 1 line patch proposed ?

yes please

@mistic100 i would even recommend it, to use random_int($min, $max) it have much better randomness

i would even recommend it, to use random_int($min, $max) it have much better randomness

There is not point in calling a slower cryptographically secure function just for random colors...