PageRenderTime 26ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/web/core/lib/Drupal/Component/Utility/Random.php

https://gitlab.com/mohamed_hussein/prodt
PHP | 304 lines | 151 code | 28 blank | 125 comment | 22 complexity | c910cf177b687ede2ecf9a536c52bc67 MD5 | raw file
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Defines a utility class for creating random data.
  5. *
  6. * @ingroup utility
  7. */
  8. class Random {
  9. /**
  10. * The maximum number of times name() and string() can loop.
  11. *
  12. * This prevents infinite loops if the length of the random value is very
  13. * small.
  14. *
  15. * @see \Drupal\Tests\Component\Utility\RandomTest
  16. */
  17. const MAXIMUM_TRIES = 100;
  18. /**
  19. * A list of unique strings generated by string().
  20. *
  21. * @var array
  22. */
  23. protected $strings = [];
  24. /**
  25. * A list of unique names generated by name().
  26. *
  27. * @var array
  28. */
  29. protected $names = [];
  30. /**
  31. * Generates a random string of ASCII characters of codes 32 to 126.
  32. *
  33. * The generated string includes alpha-numeric characters and common
  34. * miscellaneous characters. Use this method when testing general input
  35. * where the content is not restricted.
  36. *
  37. * @param int $length
  38. * Length of random string to generate.
  39. * @param bool $unique
  40. * (optional) If TRUE ensures that the random string returned is unique.
  41. * Defaults to FALSE.
  42. * @param callable $validator
  43. * (optional) A callable to validate the string. Defaults to NULL.
  44. *
  45. * @return string
  46. * Randomly generated string.
  47. *
  48. * @see \Drupal\Component\Utility\Random::name()
  49. */
  50. public function string($length = 8, $unique = FALSE, $validator = NULL) {
  51. $counter = 0;
  52. // Continue to loop if $unique is TRUE and the generated string is not
  53. // unique or if $validator is a callable that returns FALSE. To generate a
  54. // random string this loop must be carried out at least once.
  55. do {
  56. if ($counter == static::MAXIMUM_TRIES) {
  57. throw new \RuntimeException('Unable to generate a unique random name');
  58. }
  59. $str = '';
  60. for ($i = 0; $i < $length; $i++) {
  61. $str .= chr(mt_rand(32, 126));
  62. }
  63. $counter++;
  64. $continue = FALSE;
  65. if ($unique) {
  66. $continue = isset($this->strings[$str]);
  67. }
  68. if (!$continue && is_callable($validator)) {
  69. // If the validator callback returns FALSE generate another random
  70. // string.
  71. $continue = !call_user_func($validator, $str);
  72. }
  73. } while ($continue);
  74. if ($unique) {
  75. $this->strings[$str] = TRUE;
  76. }
  77. return $str;
  78. }
  79. /**
  80. * Generates a random string containing letters and numbers.
  81. *
  82. * The string will always start with a letter. The letters may be upper or
  83. * lower case. This method is better for restricted inputs that do not
  84. * accept certain characters. For example, when testing input fields that
  85. * require machine readable values (i.e. without spaces and non-standard
  86. * characters) this method is best.
  87. *
  88. * @param int $length
  89. * Length of random string to generate.
  90. * @param bool $unique
  91. * (optional) If TRUE ensures that the random string returned is unique.
  92. * Defaults to FALSE.
  93. *
  94. * @return string
  95. * Randomly generated string.
  96. *
  97. * @see \Drupal\Component\Utility\Random::string()
  98. */
  99. public function name($length = 8, $unique = FALSE) {
  100. $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
  101. $max = count($values) - 1;
  102. $counter = 0;
  103. do {
  104. if ($counter == static::MAXIMUM_TRIES) {
  105. throw new \RuntimeException('Unable to generate a unique random name');
  106. }
  107. $str = chr(mt_rand(97, 122));
  108. for ($i = 1; $i < $length; $i++) {
  109. $str .= chr($values[mt_rand(0, $max)]);
  110. }
  111. $counter++;
  112. } while ($unique && isset($this->names[$str]));
  113. if ($unique) {
  114. $this->names[$str] = TRUE;
  115. }
  116. return $str;
  117. }
  118. /**
  119. * Generate a string that looks like a word (letters only, alternating consonants and vowels).
  120. *
  121. * @param int $length
  122. * The desired word length.
  123. *
  124. * @return string
  125. */
  126. public function word($length) {
  127. $vowels = ["a", "e", "i", "o", "u"];
  128. $cons = ["b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
  129. "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr",
  130. "sl", "cl", "sh",
  131. ];
  132. $num_vowels = count($vowels);
  133. $num_cons = count($cons);
  134. $word = '';
  135. while (strlen($word) < $length) {
  136. $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
  137. }
  138. return substr($word, 0, $length);
  139. }
  140. /**
  141. * Generates a random PHP object.
  142. *
  143. * @param int $size
  144. * The number of random keys to add to the object.
  145. *
  146. * @return object
  147. * The generated object, with the specified number of random keys. Each key
  148. * has a random string value.
  149. */
  150. public function object($size = 4) {
  151. $object = new \stdClass();
  152. for ($i = 0; $i < $size; $i++) {
  153. $random_key = $this->name();
  154. $random_value = $this->string();
  155. $object->{$random_key} = $random_value;
  156. }
  157. return $object;
  158. }
  159. /**
  160. * Generates sentences Latin words, often used as placeholder text.
  161. *
  162. * @param int $min_word_count
  163. * The minimum number of words in the return string. Total word count
  164. * can slightly exceed provided this value in order to deliver
  165. * sentences of random length.
  166. * @param bool $capitalize
  167. * Uppercase all the words in the string.
  168. *
  169. * @return string
  170. * Nonsense latin words which form sentence(s).
  171. */
  172. public function sentences($min_word_count, $capitalize = FALSE) {
  173. // cSpell:disable
  174. $dictionary = ["abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
  175. "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
  176. "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
  177. "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
  178. "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
  179. "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
  180. "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
  181. "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
  182. "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
  183. "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
  184. "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
  185. "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
  186. "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
  187. "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
  188. "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
  189. "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
  190. "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
  191. "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
  192. "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
  193. "populus", "praemitto", "praesent", "premo", "probo", "proprius",
  194. "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
  195. "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
  196. "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
  197. "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
  198. "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
  199. "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
  200. "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
  201. "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
  202. "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
  203. "zelus",
  204. ];
  205. // cSpell:enable
  206. $dictionary_flipped = array_flip($dictionary);
  207. $greeking = '';
  208. if (!$capitalize) {
  209. $words_remaining = $min_word_count;
  210. while ($words_remaining > 0) {
  211. $sentence_length = mt_rand(3, 10);
  212. $words = array_rand($dictionary_flipped, $sentence_length);
  213. $sentence = implode(' ', $words);
  214. $greeking .= ucfirst($sentence) . '. ';
  215. $words_remaining -= $sentence_length;
  216. }
  217. }
  218. else {
  219. // Use slightly different method for titles.
  220. $words = array_rand($dictionary_flipped, $min_word_count);
  221. $words = is_array($words) ? implode(' ', $words) : $words;
  222. $greeking = ucwords($words);
  223. }
  224. return trim($greeking);
  225. }
  226. /**
  227. * Generate paragraphs separated by double new line.
  228. *
  229. * @param int $paragraph_count
  230. * The number of paragraphs to create. Defaults to 12.
  231. *
  232. * @return string
  233. */
  234. public function paragraphs($paragraph_count = 12) {
  235. $output = '';
  236. for ($i = 1; $i <= $paragraph_count; $i++) {
  237. $output .= $this->sentences(mt_rand(20, 60)) . "\n\n";
  238. }
  239. return $output;
  240. }
  241. /**
  242. * Create a placeholder image.
  243. *
  244. * @param string $destination
  245. * The absolute file path where the image should be stored.
  246. * @param string $min_resolution
  247. * The minimum resolution for the image. For example, '400x300'.
  248. * @param string $max_resolution
  249. * The maximum resolution for the image. For example, '800x600'.
  250. *
  251. * @return string
  252. * Path to image file.
  253. */
  254. public function image($destination, $min_resolution, $max_resolution) {
  255. $extension = pathinfo($destination, PATHINFO_EXTENSION);
  256. $min = explode('x', $min_resolution);
  257. $max = explode('x', $max_resolution);
  258. $width = rand((int) $min[0], (int) $max[0]);
  259. $height = rand((int) $min[1], (int) $max[1]);
  260. // Make an image split into 4 sections with random colors.
  261. $im = imagecreate($width, $height);
  262. for ($n = 0; $n < 4; $n++) {
  263. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
  264. $x = $width / 2 * ($n % 2);
  265. $y = $height / 2 * (int) ($n >= 2);
  266. imagefilledrectangle($im, (int) $x, (int) $y, (int) ($x + $width / 2), (int) ($y + $height / 2), $color);
  267. }
  268. // Make a perfect circle in the image middle.
  269. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
  270. $smaller_dimension = min($width, $height);
  271. imageellipse($im, (int) ($width / 2), (int) ($height / 2), $smaller_dimension, $smaller_dimension, $color);
  272. $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension);
  273. $save_function($im, $destination);
  274. return $destination;
  275. }
  276. }