Added common random string generation routine.
This commit is contained in:
parent
884d2cb9da
commit
fa67c7b0d6
1 changed files with 31 additions and 0 deletions
|
@ -5,10 +5,19 @@
|
||||||
|
|
||||||
namespace Index;
|
namespace Index;
|
||||||
|
|
||||||
|
use InvalidArgumentException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provides various helper methods for strings.
|
* Provides various helper methods for strings.
|
||||||
*/
|
*/
|
||||||
final class XString {
|
final class XString {
|
||||||
|
/**
|
||||||
|
* Default character set for the random method.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public const RANDOM_CHARS = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789';
|
||||||
|
|
||||||
public static function toBool(string $value): bool {
|
public static function toBool(string $value): bool {
|
||||||
return boolval($value);
|
return boolval($value);
|
||||||
}
|
}
|
||||||
|
@ -55,4 +64,26 @@ final class XString {
|
||||||
return true;
|
return true;
|
||||||
return empty(trim((string)$string));
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue