PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Faker/Provider/Base.php

https://github.com/kferran/Faker
PHP | 108 lines | 47 code | 13 blank | 48 comment | 1 complexity | 48eb70a1663e9b57fa0a628eb4da4d09 MD5 | raw file
  1. <?php
  2. namespace Faker\Provider;
  3. class Base
  4. {
  5. protected $generator;
  6. public function __construct($generator)
  7. {
  8. $this->generator = $generator;
  9. }
  10. /**
  11. * Returns a random number between 0 and 9
  12. *
  13. * @return integer
  14. */
  15. public static function randomDigit()
  16. {
  17. return mt_rand(0, 9);
  18. }
  19. /**
  20. * Returns a random number between 1 and 9
  21. *
  22. * @return integer
  23. */
  24. public static function randomDigitNotNull()
  25. {
  26. return mt_rand(1, 9);
  27. }
  28. /**
  29. * Returns a random number with 0 to $nbDigits digits
  30. *
  31. * @param integer $nbDigits
  32. * @example 79907610
  33. *
  34. * @return integer
  35. */
  36. public static function randomNumber($nbDigits = null)
  37. {
  38. if (null === $nbDigits) {
  39. $nbDigits = static::randomDigit();
  40. }
  41. return mt_rand(0, pow(10, $nbDigits) - 1);
  42. }
  43. /**
  44. * Returns a random letter from a to z
  45. *
  46. * @return string
  47. */
  48. public static function randomLetter()
  49. {
  50. return chr(mt_rand(97, 122));
  51. }
  52. /**
  53. * Returns a random element from a passed array
  54. *
  55. * @param array $array
  56. * @return mixed
  57. */
  58. public static function randomElement($array = array('a', 'b', 'c'))
  59. {
  60. return $array[mt_rand(0, count($array) - 1)];
  61. }
  62. /**
  63. * Replaces all hash sign ('#') occurrences with a random number
  64. * Replaces all percentage sign ('%') occurrences with a not null number
  65. *
  66. * @param string $string String that needs to bet parsed
  67. * @return string
  68. */
  69. public static function numerify($string = '###')
  70. {
  71. $string = preg_replace_callback('/\#/', 'static::randomDigit', $string);
  72. $string = preg_replace_callback('/\%/', 'static::randomDigitNotNull', $string);
  73. return $string;
  74. }
  75. /**
  76. * Replaces all question mark ('?') occurrences with a random letter
  77. *
  78. * @param string $string String that needs to bet parsed
  79. * @return string
  80. */
  81. public static function lexify($string = '????')
  82. {
  83. return preg_replace_callback('/\?/', 'static::randomLetter', $string);
  84. }
  85. /**
  86. * Replaces hash signs and question marks with random numbers and letters
  87. *
  88. * @param string $string String that needs to bet parsed
  89. * @return string
  90. */
  91. public static function bothify($string = '## ??')
  92. {
  93. return static::lexify(static::numerify($string));
  94. }
  95. }