1
0
mirror of https://github.com/processwire/processwire.git synced 2025-08-10 08:44:46 +02:00

Add new string() method to WireRandom class. This method lets you specify that it should create a random string using the given characters.

This commit is contained in:
Ryan Cramer
2025-07-23 15:11:25 -04:00
parent 27f20b4799
commit 7d5ad4b277

View File

@@ -302,6 +302,60 @@ class WireRandom extends Wire {
return $this->alphanumeric($length, $options);
}
/**
* Generate a random string using given characters
*
* @param int $length Length of string or specify 0 for random length
* @param string $characters Charaacters to use for random string or omit for partial ASCII set
* @param array $options
* - `minLength` (int): Minimum allowed length if length argument is 0 (default=10)
* - `maxLength` (int): Maximum allowed length if length argument is 0 (default=40)
* - `fast` (bool): Use a faster randomization method? (default=false)
* @return string
* @since 3.0.251
*
*/
public function string($length = 0, $characters = '', array $options = []) {
$defaults = [
'minLength' => 10,
'maxLength' => 40,
'fast' => false,
];
$options = array_merge($defaults, $options);
if(empty($characters)) {
$characters = 'abcdefghijklmnopqrstuvwxyz';
$characters .= strtoupper($characters);
$characters .= '0123456789';
$characters .= '-_;:/.,!@$%^*()-+~|';
}
if($length < 1) {
if($options['fast']) {
$length = mt_rand($options['minLength'], $options['maxLength']);
} else {
$length = $this->integer($options['minLength'], $options['maxLength']);
}
}
$str = '';
$L = strlen($characters) - 1;
for($n = 0; $n < $length; $n++) {
if($options['fast']) {
$v = mt_rand(0, $L);
} else {
$v = $this->integer(0, $L);
}
$c = substr($characters, $v, 1);
$str .= $c;
}
return $str;
}
/**
* Get a random integer
*