Completed
Push — master ( d64088...2e118b )
by Magnar Ovedal
03:11
created

Length::enforce()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
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 InvalidArgumentException;
8
use Stadly\PasswordPolice\Rule;
9
use Symfony\Component\Translation\Translator;
10
11
final class Length implements Rule
12
{
13
    /**
14
     * @var int Minimum password length.
15
     */
16
    private $min;
17
18
    /**
19
     * @var int|null Maximum password length.
20
     */
21
    private $max;
22
23 7
    public function __construct(int $min, ?int $max = null)
24
    {
25 7
        if ($min < 0) {
26 1
            throw new InvalidArgumentException('Min cannot be negative.');
27
        }
28 6
        if ($max !== null && $max < $min) {
29 1
            throw new InvalidArgumentException('Max cannot be smaller than min.');
30
        }
31 5
        if ($min === 0 && $max === null) {
32 1
            throw new InvalidArgumentException('Min cannot be zero when max is unconstrained.');
33
        }
34
35 4
        $this->min = $min;
36 4
        $this->max = $max;
37 4
    }
38
39 1
    public function getMin(): int
40
    {
41 1
        return $this->min;
42
    }
43
44 1
    public function getMax(): ?int
45
    {
46 1
        return $this->max;
47
    }
48
49 5
    public function test(string $password): bool
50
    {
51 5
        if (mb_strlen($password) < $this->min) {
52 1
            return false;
53
        }
54
55 4
        if (null !== $this->max && $this->max < mb_strlen($password)) {
56 1
            return false;
57
        }
58
59 3
        return true;
60
    }
61
62
    /**
63
     * @throws LengthException If the rule cannot be enforced.
64
     */
65 2
    public function enforce(string $password, Translator $translator): void
66
    {
67 2
        if (!$this->test($password)) {
68 1
            throw new LengthException($this, mb_strlen($password), $translator);
69
        }
70 1
    }
71
}
72