Added common random string generation routine.

This commit is contained in:
flash 2023-01-05 02:33:37 +00:00
parent 884d2cb9da
commit fa67c7b0d6

View file

@ -5,10 +5,19 @@
namespace Index;
use InvalidArgumentException;
/**
* Provides various helper methods for strings.
*/
final class XString {
/**
* Default character set for the random method.
*
* @var string
*/
public const RANDOM_CHARS = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789';
public static function toBool(string $value): bool {
return boolval($value);
}
@ -55,4 +64,26 @@ final class XString {
return true;
return empty(trim((string)$string));
}
/**
* Generates a random string of user specified length.
*
* @param int $length Desired length of the string.
* @param string $chars Set of characters to pick from. Default set contains the alphabet in upper- and lowercase and numbers 0 thru 9.
* @return string The generated string.
*/
public static function random(int $length, string $chars = self::RANDOM_CHARS): string {
if($length < 1)
throw new InvalidArgumentException('$length must be at least 1.');
if($chars === '')
throw new InvalidArgumentException('$chars may not be empty.');
$string = '';
$count = strlen($chars) - 1;
while($length-- > 0)
$string .= $chars[random_int(0, $count)];
return $string;
}
}