diff --git a/src/MicheleAngioni/Support/Helpers.php b/src/MicheleAngioni/Support/Helpers.php index 0a023ce..a874aad 100644 --- a/src/MicheleAngioni/Support/Helpers.php +++ b/src/MicheleAngioni/Support/Helpers.php @@ -166,36 +166,6 @@ static public function daysBetweenDates(string $date1, string $date2):? int // <<<--- PSEUDO-RANDOM NUMBERS METHODS --->>> - /** - * Return a random value between input $min and $max values by using the MCRYPT_DEV_URANDOM source. - * N.B. Use only on *nix servers! - * - * @param int $min = 0 - * @param int $max - * - * @return int - */ - static public function getRandomValueUrandom(int $min = 0, int $max = 0x7FFFFFFF): int - { - if ($max < $min || ($max - $min) > 0x7FFFFFFF) { - return false; - } - - $diff = $max - $min; - - $bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM); - - if ($bytes === false || strlen($bytes) != 4) { - return false; - } - - $ary = unpack("Nint", $bytes); - $val = $ary['int'] & 0x7FFFFFFF; // 32-bit safe - $fp = (float)$val / 2147483647.0; // convert to [0,1] - - return round($fp * $diff) + $min; - } - /** * Return $quantity UNIQUE random value between $min and $max. * Return null on failure. @@ -204,9 +174,9 @@ static public function getRandomValueUrandom(int $min = 0, int $max = 0x7FFFFFFF * @param int $max * @param int $quantity = 1 * - * @return array|null + * @return int[]|null */ - public function getUniqueRandomValues(int $min = 0, int $max, int $quantity = 1):? array + static public function getUniqueRandomValues(int $min = 0, int $max, int $quantity = 1):? array { if ($min > $max || $quantity < 0) { return null; @@ -215,7 +185,8 @@ public function getUniqueRandomValues(int $min = 0, int $max, int $quantity = 1) $rand = []; while (count($rand) < $quantity) { - $r = mt_rand($min, $max); + $r = random_int($min, $max); + if (!in_array($r, $rand)) { $rand[] = $r; } diff --git a/tests/HelpersTest.php b/tests/HelpersTest.php index a623cec..a70d969 100644 --- a/tests/HelpersTest.php +++ b/tests/HelpersTest.php @@ -85,9 +85,7 @@ public function testDaysBetweenDates() public function testGetUniqueRandomValues() { - $helpers = new H; - - $numbers = $helpers->getUniqueRandomValues(1, 100, 4); + $numbers = H::getUniqueRandomValues(1, 100, 4); $this->assertEquals(4, count($numbers)); $this->assertNotEquals($numbers[0], $numbers[1]); @@ -96,6 +94,10 @@ public function testGetUniqueRandomValues() $this->assertNotEquals($numbers[1], $numbers[2]); $this->assertNotEquals($numbers[1], $numbers[3]); $this->assertNotEquals($numbers[2], $numbers[3]); + $this->assertInternalType('int', $numbers[0]); + $this->assertInternalType('int', $numbers[1]); + $this->assertInternalType('int', $numbers[2]); + $this->assertInternalType('int', $numbers[3]); } public function tearDown()