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

/sites/all/modules/service_container/lib/Drupal/Component/Utility/Random.php

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