Completed
Push — master ( 83241a...8e03fe )
by Anthony
03:35
created

PasswordSpecialCharacterValidator::__construct()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 44
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 44
c 0
b 0
f 0
ccs 0
cts 42
cp 0
rs 8.8571
cc 2
eloc 38
nc 2
nop 2
crap 6
1
<?php
2
declare(strict_types=1);
3
4
namespace Porthou\Password\Validators;
5
6
use Porthou\Password\PasswordException;
7
use Porthou\Password\Validator;
8
9
class PasswordSpecialCharacterValidator implements Validator
10
{
11
    /** @var string[] $whitelist */
12
    private $whitelist;
13
    /** @var int $minimum */
14
    private $minimum;
15
16
    /**
17
     * PasswordSpecialCharacterValidator constructor.
18
     * @param int $minimum The minimum number of special characters to require.
19
     * @param string[] $whitelist The whitelist of special characters to consider valid
20
     * @see https://www.owasp.org/index.php/Password_special_characters This is the default special character whitelist
21
     */
22
    public function __construct(int $minimum = 1, array $whitelist = [])
23
    {
24
        if (empty($whitelist)) {
25
            $whitelist = [
26
                ' ',
27
                '!',
28
                '"',
29
                '#',
30
                '$',
31
                '%',
32
                '&',
33
                '\'',
34
                '(',
35
                ')',
36
                '*',
37
                '+',
38
                ',',
39
                '-',
40
                '.',
41
                '/',
42
                ':',
43
                ';',
44
                '<',
45
                '=',
46
                '>',
47
                '?',
48
                '@',
49
                '[',
50
                '\\',
51
                ']',
52
                '^',
53
                '_',
54
                '`',
55
                '{',
56
                '|',
57
                '}',
58
                '~',
59
60
            ];
61
        }
62
63
        $this->minimum = $minimum;
64
        $this->whitelist = $whitelist;
65
    }
66
67
    /** {@inheritdoc} */
68
    public function validate(string $password): bool
69
    {
70
        $pattern = '/[\\' . implode('\\', $this->whitelist) . ']/';
71
        $count = preg_match_all($pattern, $password);
72
73
        if ($count >= $this->minimum) {
74
            return true;
75
        }
76
77
        throw new PasswordException('Password must include at least ' . $this->minimum . ' special characters.');
78
    }
79
}
80