From 7d5ad4b27754e73f48be77aec3dffdd497c2fe79 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Wed, 23 Jul 2025 15:11:25 -0400 Subject: [PATCH] Add new string() method to WireRandom class. This method lets you specify that it should create a random string using the given characters. --- wire/core/WireRandom.php | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/wire/core/WireRandom.php b/wire/core/WireRandom.php index c9ed804d..e3a8b3e3 100644 --- a/wire/core/WireRandom.php +++ b/wire/core/WireRandom.php @@ -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 *