You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.7 KiB
106 lines
2.7 KiB
<?php
|
|
|
|
declare(strict_types = 1);
|
|
|
|
/**
|
|
* @author Robert Strutts
|
|
* @copyright (c) 2026, Robert Strutts
|
|
* @license MIT
|
|
*/
|
|
namespace IOcornerstone\Framework;
|
|
|
|
use IOcornerstone\Framework\Common;
|
|
|
|
/**
|
|
* random_engine - Provides a high-level API to the randomness
|
|
* provided by an Random\Engine OR uses the next Fall Back FN.
|
|
*
|
|
*/
|
|
|
|
class RandomEngine
|
|
{
|
|
private $engine = false;
|
|
|
|
public function __construct() {
|
|
$version = (float) phpversion();
|
|
if ($version > 8.1) {
|
|
$this->engine = new \Random\Randomizer();
|
|
}
|
|
}
|
|
|
|
public function getBytes(int $bytes_length = 16): string {
|
|
return ($this->engine) ? $this->engine->getBytes($bytes_length) :
|
|
random_bytes($bytes_length);
|
|
}
|
|
|
|
public function getInt(int $min, int $max): int {
|
|
if ($this->engine) {
|
|
return $this->engine->getInt($min, $max);
|
|
}
|
|
if (function_exists('random_int')) {
|
|
return random_int($min, $max); // secure fallback
|
|
} elseif (function_exists('mt_rand')) {
|
|
return mt_rand($min, $max); // fast
|
|
}
|
|
return rand($min, $max); // old
|
|
}
|
|
|
|
// Took from source https://pageconfig.com/post/fixed-length-large-random-numbers-with-php
|
|
private function bigRand(int $len = 18 ): int {
|
|
$rand = '';
|
|
while( !( isset( $rand[$len-1] ) ) ) {
|
|
$rand .= mt_rand( );
|
|
}
|
|
return (int) substr( $rand , 0 , $len );
|
|
}
|
|
|
|
public function getNextBigPostiveInt(): int {
|
|
if ($this->engine) {
|
|
return $this->engine->nextInt();
|
|
}
|
|
return $this->bigRand();
|
|
}
|
|
|
|
private function selectFromArray(array $a, int $num ): array {
|
|
$array_count = Common::getCount($a) - 1;
|
|
if ($array_count < 1) {
|
|
return [];
|
|
}
|
|
$ret = [];
|
|
for($i=0; $i<$num; $i++) {
|
|
$ret[] = $a[$this->getInt(0, $array_count)];
|
|
}
|
|
return $ret;
|
|
}
|
|
|
|
/**
|
|
* Pick random keys from an Array
|
|
*/
|
|
public function getArrayKeys(array $a, int $num): array {
|
|
if ($this->engine) {
|
|
return $this->engine->pickArrayKeys($a, $num);
|
|
}
|
|
return $this->selectFromArray($a, $num);
|
|
}
|
|
|
|
public function getShuffledArray(array $a): array {
|
|
if ($this->engine) {
|
|
return $this->engine->shuffleArray($a);
|
|
}
|
|
shuffle($a);
|
|
return $a;
|
|
}
|
|
|
|
public function getShuffledBytes(string $bytes): string {
|
|
if ($this->engine) {
|
|
return $this->engine->shuffleBytes($bytes);
|
|
}
|
|
$len = mb_strlen($bytes);
|
|
$a = [];
|
|
while($len-- > 0) {
|
|
$a[] = mb_substr($bytes, $len, 1);
|
|
}
|
|
shuffle($a);
|
|
return join('', $a);
|
|
}
|
|
}
|
|
|