|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
Password Strength Library |
|
4
|
|
|
Copyright (C) 2019 CustomerGauge |
|
5
|
|
|
[email protected] |
|
6
|
|
|
|
|
7
|
|
|
This program is free software; you can redistribute it and/or |
|
8
|
|
|
modify it under the terms of the GNU Lesser General Public |
|
9
|
|
|
License as published by the Free Software Foundation; either |
|
10
|
|
|
version 3 of the License, or (at your option) any later version. |
|
11
|
|
|
|
|
12
|
|
|
This program is distributed in the hope that it will be useful, |
|
13
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
14
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
15
|
|
|
Lesser General Public License for more details. |
|
16
|
|
|
|
|
17
|
|
|
You should have received a copy of the GNU Lesser General Public License |
|
18
|
|
|
along with this program; if not, write to the Free Software Foundation, |
|
19
|
|
|
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
|
20
|
|
|
*/ |
|
21
|
|
|
|
|
22
|
|
|
declare(strict_types=1); |
|
23
|
|
|
|
|
24
|
|
|
namespace CustomerGauge\Password; |
|
25
|
|
|
|
|
26
|
|
|
use CustomerGauge\Password\Exception\InvalidPassword; |
|
27
|
|
|
|
|
28
|
|
|
use function random_int; |
|
29
|
|
|
use function strlen; |
|
30
|
|
|
|
|
31
|
|
|
final class Generator |
|
32
|
|
|
{ |
|
33
|
|
|
private Rule $rule; |
|
34
|
|
|
|
|
35
|
|
|
private int $length; |
|
36
|
|
|
|
|
37
|
1 |
|
public function __construct(Rule $rule, int $length = 12) |
|
38
|
|
|
{ |
|
39
|
1 |
|
$this->rule = $rule; |
|
40
|
1 |
|
$this->length = $length; |
|
41
|
1 |
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
public function __invoke(): string |
|
44
|
|
|
{ |
|
45
|
|
|
try { |
|
46
|
1 |
|
$password = $this->generate(); |
|
47
|
|
|
|
|
48
|
1 |
|
$this->rule->__invoke($password); |
|
49
|
|
|
|
|
50
|
1 |
|
return $password; |
|
51
|
|
|
} catch (InvalidPassword $e) { |
|
52
|
|
|
return $this->__invoke(); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
1 |
|
public function generate(): string |
|
57
|
|
|
{ |
|
58
|
1 |
|
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|'; |
|
59
|
1 |
|
$password = ''; |
|
60
|
|
|
|
|
61
|
1 |
|
$max = strlen($chars) - 1; |
|
62
|
|
|
|
|
63
|
1 |
|
for ($i = 0; $i < $this->length; $i++) { |
|
64
|
1 |
|
$password .= $chars[random_int(0, $max)]; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
1 |
|
return $password; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|