Passed
Push — master ( 07d2e7...74ebc4 )
by Magnar Ovedal
02:39
created

ConditionalRule::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
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\Rule;
6
7
use DateTime;
8
use DateTimeInterface;
9
use StableSort\StableSort;
10
use Stadly\PasswordPolice\Constraint\DateConstraint;
11
use Stadly\PasswordPolice\Password;
12
use Stadly\PasswordPolice\Policy;
13
use Stadly\PasswordPolice\Rule;
14
use Stadly\PasswordPolice\ValidationError;
15
16
final class ConditionalRule implements Rule
17
{
18
    /**
19
     * @var Rule Rule to test conditionally.
20
     */
21
    private $rule;
22
23
    /**
24
     * @var callable(Password|string): bool Condition function.
25
     */
26
    private $condition;
27
28
    /**
29
     * @param Rule $rule Rule to test if the condition is true.
30
     * @param callable(Password|string): bool $condition Condition function.
31
     */
32 4
    public function __construct(Rule $rule, callable $condition)
33
    {
34 4
        $this->rule = $rule;
35 4
        $this->condition = $condition;
36 4
    }
37
38
    /**
39
     * {@inheritDoc}
40
     */
41 2
    public function test($password, ?int $weight = 1): bool
42
    {
43 2
        if (($this->condition)($password)) {
44 1
            return $this->rule->test($password, $weight);
45
        }
46
47 1
        return true;
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     */
53 2
    public function validate($password): ?ValidationError
54
    {
55 2
        if (($this->condition)($password)) {
56 1
            return $this->rule->validate($password);
57
        }
58
59 1
        return null;
60
    }
61
}
62