Completed
Push — master ( 46548b...894271 )
by Magnar Ovedal
03:45
created

PositionConstraint::test()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\PasswordPolice\Constraint;
6
7
use InvalidArgumentException;
8
9
final class PositionConstraint
10
{
11
    /**
12
     * @var int First position.
13
     */
14
    private $first;
15
16
    /**
17
     * @var int|null Number of positions.
18
     */
19
    private $count;
20
21
    /**
22
     * @var int Constraint weight.
23
     */
24
    private $weight;
25
26
    /**
27
     * @param int $first First position.
28
     * @param int|null $count Number of positions.
29
     * @param int $weight Constraint weight.
30
     */
31 9
    public function __construct(int $first = 0, ?int $count = null, int $weight = 1)
32
    {
33 9
        if ($first < 0) {
34 1
            throw new InvalidArgumentException('First cannot be negative.');
35
        }
36 8
        if ($count !== null && $count < 1) {
37 2
            throw new InvalidArgumentException('Count must be positive.');
38
        }
39
40 6
        $this->first = $first;
41 6
        $this->count = $count;
42 6
        $this->weight = $weight;
43 6
    }
44
45
    /**
46
     * @return int First position.
47
     */
48 1
    public function getFirst(): int
49
    {
50 1
        return $this->first;
51
    }
52
53
    /**
54
     * @return int|null Number of positions.
55
     */
56 1
    public function getCount(): ?int
57
    {
58 1
        return $this->count;
59
    }
60
61
    /**
62
     * @return int Constraint weight.
63
     */
64 1
    public function getWeight(): int
65
    {
66 1
        return $this->weight;
67
    }
68
69
    /**
70
     * Check whether the position is in compliance with the constraint.
71
     *
72
     * @param int $pos Position to check.
73
     * @return bool Whether the position is in compliance with the constraint.
74
     */
75 4
    public function test(int $pos): bool
76
    {
77 4
        if ($pos < $this->first) {
78 1
            return false;
79
        }
80
81 3
        if ($this->count !== null && $this->first+$this->count <= $pos) {
82 1
            return false;
83
        }
84
85 2
        return true;
86
    }
87
}
88