RandomStringGenerator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper;
  3. /**
  4. * Helper for generating random strings
  5. *
  6. * @author Sławomir Miśkowicz <slawomir@modulesgarden.com>
  7. */
  8. class RandomStringGenerator
  9. {
  10. protected $stringLength = 10;
  11. protected $charSet = '';
  12. protected $upperCharSet = 'QWERTYUIOPLKJHGFDSAZXCVBNM';
  13. protected $lowerCharSet = 'qwertyuioplkjhgfdsazxcvbnm';
  14. protected $numbersCharSet = '0123456789';
  15. protected $useUppercase = false;
  16. protected $useLowercase = true;
  17. protected $useNumbers = true;
  18. public function __construct($stringLength = null, $useNumbers = true, $useLowercase = true, $useUppercase = false)
  19. {
  20. $this->setLength($stringLength);
  21. $this->setUseNumbers($useNumbers);
  22. $this->setUseUppercase($useUppercase);
  23. $this->setUseLowercase($useLowercase);
  24. }
  25. public function setLength($stringLength)
  26. {
  27. if ((int) $stringLength > 0)
  28. {
  29. $this->stringLength = (int) $stringLength;
  30. }
  31. }
  32. public function genRandomString($const = null)
  33. {
  34. $randString = '';
  35. while (strlen($randString) < $this->stringLength)
  36. {
  37. $number = rand(0, strlen($this->charSet) - 1);
  38. $randString .= $this->charSet[$number];
  39. }
  40. if (is_string($const))
  41. {
  42. $randString = $const . '_' . $randString;
  43. }
  44. return $randString;
  45. }
  46. public function loadCharSet()
  47. {
  48. $this->charSet = '';
  49. if ($this->useNumbers)
  50. {
  51. $this->charSet .= $this->numbersCharSet;
  52. }
  53. if ($this->useLowercase)
  54. {
  55. $this->charSet .= $this->lowerCharSet;
  56. }
  57. if ($this->useUppercase)
  58. {
  59. $this->charSet .= $this->upperCharSet;
  60. }
  61. //use default set if someone disables all sets
  62. if ($this->charSet === '')
  63. {
  64. $this->charSet = $this->numbersCharSet . $this->lowerCharSet;
  65. }
  66. }
  67. public function setUseNumbers($value = true)
  68. {
  69. if (is_bool($value))
  70. {
  71. $this->useNumbers = $value;
  72. }
  73. $this->loadCharSet();
  74. }
  75. public function setUseLowercase($value = true)
  76. {
  77. if (is_bool($value))
  78. {
  79. $this->useLowercase = $value;
  80. }
  81. $this->loadCharSet();
  82. }
  83. public function setUseUppercase($value = true)
  84. {
  85. if (is_bool($value))
  86. {
  87. $this->useUppercase = $value;
  88. }
  89. $this->loadCharSet();
  90. }
  91. }