Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By mr.baileys on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Introduced in version:
Issue links:
Description:
- Methods on \Drupal\Component\Utility\Random are no longer static which makes unit testing possible.
- An optional $validator parameter has been added added to
\Drupal\Component\Utility\Random::string()
. The parameter takes a callable that returns TRUE if the generated string is valid, FALSE otherwise. In case of an invalid string, Random::string() will attempt to generate a new random string until the string is valid orMAXIMUM_TRIES
is reached.
Before
$string = Random::string(8);
After
$random_generator = new Random();
$string = $random_generator->string(8);
The $validator callable can be used to discard randomly generated strings that are invalid. The example below ensures that randomly generated strings do not start with a digit.
class RandomExample {
public function generateString() {
$random_generator = new Random();
return $random_generator->string(8, TRUE, array($this, 'randomStringValidate'));
}
/**
* Callback for random string validation.
*/
public function randomStringValidate($string) {
// Reject random strings that start with a digit.
if (preg_match('/^\d/', $string)) {
return FALSE;
}
return TRUE;
}
}
Impacts:
Module developers