From fa67c7b0d6fa01d2bff6b7abc418f306440740b2 Mon Sep 17 00:00:00 2001 From: flashwave Date: Thu, 5 Jan 2023 02:33:37 +0000 Subject: [PATCH] Added common random string generation routine. --- src/XString.php | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/XString.php b/src/XString.php index 5850a1c..5cbbc2b 100644 --- a/src/XString.php +++ b/src/XString.php @@ -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; + } }