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

Length   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 58
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0
wmc 14

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getMax() 0 3 1
A getMin() 0 3 1
A enforce() 0 4 2
A test() 0 11 4
A __construct() 0 14 6
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