randomMachineName() should conform to processMachineName() pattern

Created on 13 May 2018, over 6 years ago
Updated 24 July 2023, over 1 year ago

Problem/Motivation

@alexpott:

By default a machine name can only contain lowercase. 'replace_pattern' => '[^a-z0-9_]+', from \Drupal\Core\Render\Element\MachineName::processMachineName(). I think the random machine name generated should conform to our default regex.

Current code:

# Drupal\Tests\UnitTestCase
public function randomMachineName($length = 8) {
  return $this->getRandomGenerator()->name($length, TRUE);
}


# Drupal\Component\Utility\Random
  /**
   * Generates a random string containing letters and numbers.
   *
   * The string will always start with a letter. The letters may be upper or
   * lower case ...
   */
  public function name($length = 8, $unique = FALSE) {
    ...
  }

Why upper and lower mix can be a problem:

1. It can be the cause of random fails in tests that use randomMachineName() like value for UI field. Because the value will be automatically converted to lowercase, which does not mean its unique.
Example (psedo code):

createFieldById('Value'); #Ok, 'Value' -> 'value'.
createFieldById('VALUE'); #Error, 'VALUE' -> 'value', but the field with id "value" already exists

2. It also causes inconvenience when assert expected and actual id:

$expected = randomMachineName();
$field = createFieldById($expected);
$actual = $field->id();

Or when creating other instances, example:

# Drupal\Component\Utility::getId()
$id = str_replace([' ', '_', '[', ']'], ['-', '-', '-', ''], mb_strtolower($id));

3. It also causes conflicts with other places because only lowercase for id is a common practice.

Proposed resolution

Add new Random::machineName() function which is used by RandomGeneratorTrait::randomMachineName() and UnitTestCase::randomMachineName()
This new function generates a random machine name containing only lower case letters and numbers. A RuntimeException is thrown when a unique machine name can't be generated within 100 tries.

Remaining tasks

User interface changes

API changes

Data model changes

📌 Task
Status

Fixed

Version

11.0 🔥

Component
PHPUnit 

Last updated about 3 hours ago

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024