PageRenderTime 46ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/reasonat/test8
PHP | 299 lines | 150 code | 30 blank | 119 comment | 22 complexity | 6dd64f9d87650bd0fab96847ae2e2a07 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 = array();
  24. /**
  25. * A list of unique names generated by name().
  26. *
  27. * @var array
  28. */
  29. protected $names = array();
  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. mt_srand((double) microtime() * 1000000);
  128. $vowels = array("a", "e", "i", "o", "u");
  129. $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
  130. "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl", "sh");
  131. $num_vowels = count($vowels);
  132. $num_cons = count($cons);
  133. $word = '';
  134. while (strlen($word) < $length) {
  135. $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
  136. }
  137. return substr($word, 0, $length);
  138. }
  139. /**
  140. * Generates a random PHP object.
  141. *
  142. * @param int $size
  143. * The number of random keys to add to the object.
  144. *
  145. * @return \stdClass
  146. * The generated object, with the specified number of random keys. Each key
  147. * has a random string value.
  148. */
  149. public function object($size = 4) {
  150. $object = new \stdClass();
  151. for ($i = 0; $i < $size; $i++) {
  152. $random_key = $this->name();
  153. $random_value = $this->string();
  154. $object->{$random_key} = $random_value;
  155. }
  156. return $object;
  157. }
  158. /**
  159. * Generates sentences Latin words, often used as placeholder text.
  160. *
  161. * @param int $min_word_count
  162. * The minimum number of words in the return string. Total word count
  163. * can slightly exceed provided this value in order to deliver
  164. * sentences of random length.
  165. * @param bool $capitalize
  166. * Uppercase all the words in the string.
  167. *
  168. * @return string
  169. * Nonsense latin words which form sentence(s).
  170. */
  171. public function sentences($min_word_count, $capitalize = FALSE) {
  172. $dictionary = array("abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
  173. "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
  174. "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
  175. "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
  176. "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
  177. "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
  178. "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
  179. "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
  180. "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
  181. "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
  182. "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
  183. "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
  184. "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
  185. "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
  186. "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
  187. "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
  188. "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
  189. "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
  190. "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
  191. "populus", "praemitto", "praesent", "premo", "probo", "proprius",
  192. "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
  193. "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
  194. "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
  195. "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
  196. "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
  197. "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
  198. "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
  199. "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
  200. "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
  201. "zelus");
  202. $dictionary_flipped = array_flip($dictionary);
  203. $greeking = '';
  204. if (!$capitalize) {
  205. $words_remaining = $min_word_count;
  206. while ($words_remaining > 0) {
  207. $sentence_length = mt_rand(3, 10);
  208. $words = array_rand($dictionary_flipped, $sentence_length);
  209. $sentence = implode(' ', $words);
  210. $greeking .= ucfirst($sentence) . '. ';
  211. $words_remaining -= $sentence_length;
  212. }
  213. }
  214. else {
  215. // Use slightly different method for titles.
  216. $words = array_rand($dictionary_flipped, $min_word_count);
  217. $words = is_array($words) ? implode(' ', $words) : $words;
  218. $greeking = ucwords($words);
  219. }
  220. return trim($greeking);
  221. }
  222. /**
  223. * Generate paragraphs separated by double new line.
  224. *
  225. * @param int $paragraph_count
  226. * @return string
  227. */
  228. public function paragraphs($paragraph_count = 12) {
  229. $output = '';
  230. for ($i = 1; $i <= $paragraph_count; $i++) {
  231. $output .= $this->sentences(mt_rand(20, 60)) . "\n\n";
  232. }
  233. return $output;
  234. }
  235. /**
  236. * Create a placeholder image.
  237. *
  238. * @param string $destination
  239. * The absolute file path where the image should be stored.
  240. * @param int $min_resolution
  241. * @param int $max_resolution
  242. *
  243. * @return string
  244. * Path to image file.
  245. */
  246. public function image($destination, $min_resolution, $max_resolution) {
  247. $extension = pathinfo($destination, PATHINFO_EXTENSION);
  248. $min = explode('x', $min_resolution);
  249. $max = explode('x', $max_resolution);
  250. $width = rand((int) $min[0], (int) $max[0]);
  251. $height = rand((int) $min[1], (int) $max[1]);
  252. // Make an image split into 4 sections with random colors.
  253. $im = imagecreate($width, $height);
  254. for ($n = 0; $n < 4; $n++) {
  255. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
  256. $x = $width / 2 * ($n % 2);
  257. $y = $height / 2 * (int) ($n >= 2);
  258. imagefilledrectangle($im, $x, $y, $x + $width / 2, $y + $height / 2, $color);
  259. }
  260. // Make a perfect circle in the image middle.
  261. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
  262. $smaller_dimension = min($width, $height);
  263. $smaller_dimension = ($smaller_dimension % 2) ? $smaller_dimension : $smaller_dimension;
  264. imageellipse($im, $width / 2, $height / 2, $smaller_dimension, $smaller_dimension, $color);
  265. $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension);
  266. $save_function($im, $destination);
  267. return $destination;
  268. }
  269. }