public function getRandomString($length, $chars = null)
{
if ($length < 1) {
throw new \InvalidArgumentException('Length should be >= 1');
}
if (empty($chars)) {
$numBytes = ceil($length * 0.75);
$bytes = $this->getRandomBytes($numBytes);
$string = substr(rtrim(base64_encode($bytes), '='), 0, $length);
// Base64 URL
return strtr($string, '+/', '-_');
}
if ($chars == self::CHARS_HEX) {
// hex is easy
$bytes = $this->getRandomBytes(ceil($length / 2));
return substr(bin2hex($bytes), 0, $length);
}
$listLen = strlen($chars);
if ($listLen == 1) {
return str_repeat($chars, $length);
}
$bytes = $this->getRandomBytes($length);
$pos = 0;
$result = '';
for ($i = 0; $i < $length; $i++) {
$pos = ($pos + ord($bytes[$i])) % $listLen;
$result .= $chars[$pos];
}
return $result;
}