summaryrefslogtreecommitdiffstatshomepage
path: root/core/tests/Drupal/Tests/RandomGeneratorTrait.php
blob: e2f964b1065e53db1824814791da888f6746cd09 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php

declare(strict_types=1);

namespace Drupal\Tests;

use Drupal\TestTools\Random;

/**
 * Provides random generator utility methods.
 */
trait RandomGeneratorTrait {

  /**
   * 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.
   *
   * @param int $length
   *   Length of random string to generate.
   *
   * @return string
   *   Pseudo-randomly generated unique string including special characters.
   *
   * @see \Drupal\Component\Utility\Random::string()
   */
  public function randomString($length = 8) {
    return Random::string($length);
  }

  /**
   * Generates a unique random string containing letters and numbers.
   *
   * Do not use this method when testing non validated user input. Instead, use
   * \Drupal\Tests\RandomGeneratorTrait::randomString().
   *
   * @param int $length
   *   Length of random string to generate.
   *
   * @return string
   *   Randomly generated unique string.
   *
   * @see \Drupal\Component\Utility\Random::name()
   */
  protected function randomMachineName($length = 8): string {
    return Random::machineName($length);
  }

  /**
   * Generates a random PHP object.
   *
   * @param int $size
   *   The number of random keys to add to the object.
   *
   * @return object
   *   The generated object, with the specified number of random keys. Each key
   *   has a random string value.
   *
   * @see \Drupal\Component\Utility\Random::object()
   */
  public function randomObject($size = 4) {
    return Random::object($size);
  }

  /**
   * Gets the random generator for the utility methods.
   *
   * @return \Drupal\Component\Utility\Random
   *   The random generator.
   */
  protected function getRandomGenerator() {
    return Random::getGenerator();
  }

}