function Random::machineName

Same name in this branch
  1. 11.x core/tests/Drupal/TestTools/Random.php \Drupal\TestTools\Random::machineName()
Same name and namespace in other branches
  1. 10 core/tests/Drupal/TestTools/Random.php \Drupal\TestTools\Random::machineName()
  2. 10 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::machineName()

Generates a string containing lowercase letters and numbers.

This method is used to generate strings that are compliant with Drupal machine names. This doesn't include underscores, dashes and periods since those are not compatible with all machine names.

Parameters

int $length: Length of random string to generate.

bool $unique: If TRUE ensures that the random string returned is unique. Defaults to FALSE.

Return value

string Randomly generated string.

Throws

\RuntimeException Thrown if a unique machine name cannot be generated within the allowed number of random attempts.

See also

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

File

core/lib/Drupal/Component/Utility/Random.php, line 162

Class

Random
Defines a utility class for creating random data.

Namespace

Drupal\Component\Utility

Code

public function machineName(int $length = 8, bool $unique = FALSE) : string {
    $values = array_merge(range('a', 'z'), range(0, 9));
    $start_characters = range('a', 'z');
    $counter = 0;
    do {
        if ($counter == static::MAXIMUM_TRIES) {
            throw new \RuntimeException('Unable to generate a unique random machine name');
        }
        $str = $start_characters[array_rand($start_characters)];
        for ($i = 1; $i < $length; $i++) {
            $str .= $values[array_rand($values)];
        }
        $counter++;
    } while ($unique && isset($this->machineNames[$str]));
    if ($unique) {
        $this->machineNames[$str] = TRUE;
    }
    return $str;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.