|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Sludio\HelperBundle\Script\Utils; |
|
4
|
|
|
|
|
5
|
|
|
class Generator |
|
6
|
|
|
{ |
|
7
|
|
|
const PASS_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'; |
|
8
|
|
|
const PASS_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
|
9
|
|
|
const PASS_DIGITS = '0123456789'; |
|
10
|
|
|
const PASS_SYMBOLS = '!@#$%^&*()_-=+;:.,?'; |
|
11
|
|
|
|
|
12
|
|
|
const RAND_BASIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
|
13
|
|
|
const RAND_EXTENDED = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-=+;:,.?'; |
|
14
|
|
|
|
|
15
|
|
|
private $sets = []; |
|
16
|
|
|
|
|
17
|
|
|
public function generate($length = 20) |
|
18
|
|
|
{ |
|
19
|
|
|
$all = ''; |
|
20
|
|
|
$password = ''; |
|
21
|
|
|
foreach ($this->sets as $set) { |
|
22
|
|
|
$password .= $set[$this->tweak(str_split($set))]; |
|
23
|
|
|
$all .= $set; |
|
24
|
|
|
} |
|
25
|
|
|
$all = str_split($all); |
|
26
|
|
|
for ($i = 0; $i < $length - count($this->sets); $i++) { |
|
27
|
|
|
$password .= $all[$this->tweak($all)]; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return str_shuffle($password); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function tweak($array) |
|
34
|
|
|
{ |
|
35
|
|
|
if (function_exists('random_int')) { |
|
36
|
|
|
return random_int(0, count($array) - 1); |
|
37
|
|
|
} elseif (function_exists('mt_rand')) { |
|
38
|
|
|
return mt_rand(0, count($array) - 1); |
|
39
|
|
|
} else { |
|
40
|
|
|
return array_rand($array); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function useLower() |
|
45
|
|
|
{ |
|
46
|
|
|
$this->sets['lower'] = self::PASS_LOWERCASE; |
|
47
|
|
|
|
|
48
|
|
|
return $this; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function useUpper() |
|
52
|
|
|
{ |
|
53
|
|
|
$this->sets['upper'] = self::PASS_UPPERCASE; |
|
54
|
|
|
|
|
55
|
|
|
return $this; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function useDigits() |
|
59
|
|
|
{ |
|
60
|
|
|
$this->sets['digits'] = self::PASS_DIGITS; |
|
61
|
|
|
|
|
62
|
|
|
return $this; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
public function useSymbols() |
|
66
|
|
|
{ |
|
67
|
|
|
$this->sets['symbols'] = self::PASS_SYMBOLS; |
|
68
|
|
|
|
|
69
|
|
|
return $this; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
public static function getRandomString($length = 20, $chars = self::RAND_BASIC) |
|
73
|
|
|
{ |
|
74
|
|
|
return substr(str_shuffle(str_repeat($chars, (int)ceil((int)($length / \strlen($chars))))), 1, $length); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
public static function getUniqueId($length = 20) |
|
78
|
|
|
{ |
|
79
|
|
|
try { |
|
80
|
|
|
return bin2hex(random_bytes($length)); |
|
81
|
|
|
} catch (\Exception $exception) { |
|
82
|
|
|
return self::getRandomString($length); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|