Passed
Push — master ( 30b9f9...28ee83 )
by Magnar Ovedal
02:55
created

Policy::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
0 ignored issues
show
Documentation Bug introduced by
The doc comment RuleInterface... at position 0 could not be parsed: Unknown type name 'RuleInterface...' at position 0 in RuleInterface....
Loading history...
20
     */
21 3
    public function __construct(RuleInterface... $rules)
22
    {
23 3
        $this->addRules(...$rules);
24 3
    }
25
26
    /**
27
     * @param RuleInterface... $rules Policy rules
0 ignored issues
show
Documentation Bug introduced by
The doc comment RuleInterface... at position 0 could not be parsed: Unknown type name 'RuleInterface...' at position 0 in RuleInterface....
Loading history...
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