Change record status: 
Project: 
Introduced in branch: 
8.x
Introduced in version: 
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 or MAXIMUM_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
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done
Details: 
Progress: