1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Stadly\PasswordPolice; |
6
|
|
|
|
7
|
|
|
use Symfony\Component\Translation\Translator; |
8
|
|
|
use Stadly\PasswordPolice\Rule\RuleException; |
9
|
|
|
use Stadly\PasswordPolice\Rule\RuleInterface; |
10
|
|
|
|
11
|
|
|
final class Policy |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var RuleInterface[] Policy rules. |
15
|
|
|
*/ |
16
|
|
|
private $rules = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param RuleInterface... $rules Policy rules |
|
|
|
|
20
|
|
|
*/ |
21
|
3 |
|
public function __construct(RuleInterface... $rules) |
22
|
|
|
{ |
23
|
3 |
|
$this->addRules(...$rules); |
24
|
3 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param RuleInterface... $rules Policy rules |
|
|
|
|
28
|
|
|
*/ |
29
|
3 |
|
public function addRules(RuleInterface... $rules): void |
30
|
|
|
{ |
31
|
3 |
|
foreach ($rules as $rule) { |
32
|
3 |
|
$this->rules[] = $rule; |
33
|
|
|
} |
34
|
3 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Check whether a password adheres to the policy. |
38
|
|
|
* |
39
|
|
|
* @param string $password Password to check. |
40
|
|
|
* @return bool Whether the password adheres to the policy. |
41
|
|
|
*/ |
42
|
5 |
|
public function test(string $password): bool |
43
|
|
|
{ |
44
|
5 |
|
foreach ($this->rules as $rule) { |
45
|
4 |
|
if (!$rule->test($password)) { |
46
|
4 |
|
return false; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
3 |
|
return true; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Enforce that a password adheres to the policy. |
55
|
|
|
* |
56
|
|
|
* @param string $password Password that must adhere to the policy. |
57
|
|
|
* @param Translator $translator For translating messages. |
58
|
|
|
* @throws PolicyException If the password does not adhrere to the policy. |
59
|
|
|
*/ |
60
|
2 |
|
public function enforce(string $password, Translator $translator): void |
61
|
|
|
{ |
62
|
2 |
|
$exceptions = []; |
63
|
|
|
|
64
|
2 |
|
foreach ($this->rules as $rule) { |
65
|
|
|
try { |
66
|
1 |
|
$rule->enforce($password, $translator); |
67
|
1 |
|
} catch (RuleException $exception) { |
68
|
1 |
|
$exceptions[] = $exception; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
2 |
|
if ($exceptions !== []) { |
73
|
1 |
|
throw new PolicyException($this, $exceptions); |
74
|
|
|
} |
75
|
1 |
|
} |
76
|
|
|
} |
77
|
|
|
|