function Random::string

Same name in this branch
  1. 10 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::string()
Same name and namespace in other branches
  1. 9 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::string()
  2. 8.9.x core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::string()
  3. 11.x core/tests/Drupal/TestTools/Random.php \Drupal\TestTools\Random::string()
  4. 11.x core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::string()

Generates a pseudo-random string of ASCII characters of codes 32 to 126.

Do not use this method when special characters are not possible (e.g., in machine or file names that have already been validated); instead, use \Drupal\Tests\RandomGeneratorTrait::randomMachineName(). If $length is greater than 3 the random string will include at least one ampersand ('&') and at least one greater than ('>') character to ensure coverage for special characters and avoid the introduction of random test failures.

Parameters

int $length: Length of random string to generate.

Return value

string Pseudo-randomly generated unique string including special characters.

See also

\Drupal\Component\Utility\Random::string()

4 calls to Random::string()
CacheCollectorTest::providerTestInvalidCharacters in core/tests/Drupal/KernelTests/Core/Cache/CacheCollectorTest.php
Data provider for ::testCacheCollector().
OEmbedIframeControllerTest::providerBadHashParameter in core/modules/media/tests/src/Kernel/OEmbedIframeControllerTest.php
Data provider for testBadHashParameter().
QueryBatchTest::queryDataProvider in core/modules/migrate/tests/src/Kernel/QueryBatchTest.php
RandomGeneratorTrait::randomString in core/tests/Drupal/Tests/RandomGeneratorTrait.php
Generates a pseudo-random string of ASCII characters of codes 32 to 126.

File

core/tests/Drupal/TestTools/Random.php, line 50

Class

Random
Provides random generator utility static methods.

Namespace

Drupal\TestTools

Code

public static function string(int $length = 8) : string {
    if ($length < 4) {
        return static::getGenerator()->string($length, TRUE, [
            static::class,
            'stringValidate',
        ]);
    }
    // To prevent the introduction of random test failures, ensure that the
    // returned string contains a character that needs to be escaped in HTML by
    // injecting an ampersand into it.
    $replacement_pos = intval($length / 2);
    // Remove 2 from the length to account for the ampersand and greater than
    // characters.
    $string = static::getGenerator()->string($length - 2, TRUE, [
        static::class,
        'stringValidate',
    ]);
    return substr_replace($string, '>&', $replacement_pos, 0);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.