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.




