Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. Random.php

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

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal