Completed
Push — master ( a39021...04083f )
by Magnar Ovedal
04:44 queued 01:13
created

LengthRule::__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 3
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\Rule;
6
7
use StableSort\StableSort;
8
use Stadly\PasswordPolice\Constraint\CountConstraint;
9
use Stadly\PasswordPolice\Password;
10
use Stadly\PasswordPolice\Policy;
11
use Stadly\PasswordPolice\Rule;
12
use Stadly\PasswordPolice\ValidationError;
13
14
final class LengthRule implements Rule
15
{
16
    /**
17
     * @var CountConstraint[] Rule constraints.
18
     */
19
    private $constraints;
20
21
    /**
22
     * @param int $min Minimum password length.
23
     * @param int|null $max Maximum password length.
24
     * @param int $weight Constraint weight.
25
     */
26 7
    public function __construct(int $min = 8, ?int $max = null, int $weight = 1)
27
    {
28 7
        $this->addConstraint($min, $max, $weight);
29 5
    }
30
31
    /**
32
     * @param int $min Minimum password length.
33
     * @param int|null $max Maximum password length.
34
     * @param int $weight Constraint weight.
35
     * @return $this
36
     */
37 2
    public function addConstraint(int $min = 8, ?int $max = null, int $weight = 1): self
38
    {
39 2
        $this->constraints[] = new CountConstraint($min, $max, $weight);
40
41
        StableSort::usort($this->constraints, static function (CountConstraint $a, CountConstraint $b): int {
42 2
            return $b->getWeight() <=> $a->getWeight();
43 2
        });
44
45 2
        return $this;
46
    }
47
48
    /**
49
     * Check whether a password is in compliance with the rule.
50
     *
51
     * @param Password|string $password Password to check.
52
     * @param int|null $weight Don't consider constraints with lower weights.
53
     * @return bool Whether the password is in compliance with the rule.
54
     */
55 6
    public function test($password, ?int $weight = 1): bool
56
    {
57 6
        $count = $this->getCount((string)$password);
58 6
        $constraint = $this->getViolation($count, $weight);
59
60 6
        return $constraint === null;
61
    }
62
63
    /**
64
     * Validate that a password is in compliance with the rule.
65
     *
66
     * @param Password|string $password Password to validate.
67
     * @return ValidationError|null Validation error describing why the password is not in compliance with the rule.
68
     */
69 6
    public function validate($password): ?ValidationError
70
    {
71 6
        $count = $this->getCount((string)$password);
72 6
        $constraint = $this->getViolation($count);
73
74 6
        if ($constraint !== null) {
75 5
            return new ValidationError(
76 5
                $this->getMessage($constraint, $count),
77 5
                $password,
78 5
                $this,
79 5
                $constraint->getWeight()
80
            );
81
        }
82
83 1
        return null;
84
    }
85
86
    /**
87
     * @param int $count Number of characters.
88
     * @param int|null $weight Don't consider constraints with lower weights.
89
     * @return CountConstraint|null Constraint violated by the count.
90
     */
91 12
    private function getViolation(int $count, ?int $weight = null): ?CountConstraint
92
    {
93 12
        foreach ($this->constraints as $constraint) {
94 12
            if ($weight !== null && $constraint->getWeight() < $weight) {
95 1
                continue;
96
            }
97 11
            if (!$constraint->test($count)) {
98 11
                return $constraint;
99
            }
100
        }
101
102 5
        return null;
103
    }
104
105
    /**
106
     * @param string $password Password to count characters in.
107
     * @return int Number of characters.
108
     */
109 12
    private function getCount(string $password): int
110
    {
111 12
        return mb_strlen($password);
112
    }
113
114
    /**
115
     * @param CountConstraint $constraint Constraint that is violated.
116
     * @param int $count Count that violates the constraint.
117
     * @return string Message explaining the violation.
118
     */
119 5
    private function getMessage(CountConstraint $constraint, int $count): string
0 ignored issues
show
Unused Code introduced by
The parameter $count is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

119
    private function getMessage(CountConstraint $constraint, /** @scrutinizer ignore-unused */ int $count): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
120
    {
121 5
        $translator = Policy::getTranslator();
122
123 5
        if ($constraint->getMax() === null) {
124 1
            return $translator->trans(
125
                'There must be at least one character.|'.
126 1
                'There must be at least %count% characters.',
127 1
                ['%count%' => $constraint->getMin()]
128
            );
129
        }
130
131 4
        if ($constraint->getMax() === 0) {
132 1
            return $translator->trans(
133 1
                'There must be no characters.'
134
            );
135
        }
136
137 3
        if ($constraint->getMin() === 0) {
138 1
            return $translator->trans(
139
                'There must be at most one character.|'.
140 1
                'There must be at most %count% characters.',
141 1
                ['%count%' => $constraint->getMax()]
142
            );
143
        }
144
145 2
        if ($constraint->getMin() === $constraint->getMax()) {
146 1
            return $translator->trans(
147
                'There must be exactly one character.|'.
148 1
                'There must be exactly %count% characters.',
149 1
                ['%count%' => $constraint->getMin()]
150
            );
151
        }
152
153 1
        return $translator->trans(
154 1
            'There must be between %min% and %max% characters.',
155 1
            ['%min%' => $constraint->getMin(), '%max%' => $constraint->getMax()]
156
        );
157
    }
158
}
159