PasswordSpecialCharacterValidator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
eloc 45
dl 0
loc 69
c 0
b 0
f 0
ccs 0
cts 50
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 10 2
A __construct() 0 43 2
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