You are here

public function Random::string in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::string()

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.

Parameters

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.

Return value

string Randomly generated string.

See also

\Drupal\Component\Utility\Random::name()

1 call to Random::string()
Random::object in core/lib/Drupal/Component/Utility/Random.php
Generates a random PHP object.

File

core/lib/Drupal/Component/Utility/Random.php, line 61
Contains \Drupal\Component\Utility\Random.

Class

Random
Defines a utility class for creating random data.

Namespace

Drupal\Component\Utility

Code

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;
}