public Random::string($length = 8, $unique = FALSE, $validator = NULL)
Generates a random string of ASCII characters of codes 32 to 126.
The generated string includes alpha-numeric characters and common miscellaneous characters. Use this method when testing general input where the content is not restricted.
int $length: Length of random string to generate.
bool $unique: (optional) If TRUE ensures that the random string returned is unique. Defaults to FALSE.
callable $validator: (optional) A callable to validate the string. Defaults to NULL.
string Randomly generated string.
\Drupal\Component\Utility\Random::name()
public function string($length = 8, $unique = FALSE, $validator = NULL) { $counter = 0; // Continue to loop if $unique is TRUE and the generated string is not // unique or if $validator is a callable that returns FALSE. To generate a // random string this loop must be carried out at least once. do { if ($counter == static::MAXIMUM_TRIES) { throw new \RuntimeException('Unable to generate a unique random name'); } $str = ''; for ($i = 0; $i < $length; $i++) { $str .= chr(mt_rand(32, 126)); } $counter++; $continue = FALSE; if ($unique) { $continue = isset($this->strings[$str]); } if (!$continue && is_callable($validator)) { // If the validator callback returns FALSE generate another random // string. $continue = !call_user_func($validator, $str); } } while ($continue); if ($unique) { $this->strings[$str] = TRUE; } return $str; }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Utility!Random.php/function/Random::string/8.1.x