Completed
Branch v2.0.0 (e47d62)
by Alexander
03:40
created

UserPasswordSpecification::validate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * @author Alexander Torosh <[email protected]>
4
 */
5
6
namespace Domain\User\Specifications;
7
8
use Domain\User\Exceptions\UserSpecificationException;
9
10
class UserPasswordSpecification
11
{
12
    private $password;
13
14
    public function __construct($password)
15
    {
16
        $this->password = trim(strval($password));
17
    }
18
19
    public function validate()
20
    {
21
        $this->validateLength();
22
        $this->validateLetters();
23
        $this->validateNumbers();
24
        $this->validateCaseDiff();
25
        $this->validateWeakPasswords();
26
    }
27
28
    private function validateLength()
29
    {
30
        $length = mb_strlen($this->password);
31
32
        if ($length < 8) {
33
            throw new UserSpecificationException('Password length must be at least 8 characters.');
34
        }
35
    }
36
37
    private function validateLetters()
38
    {
39
        if (0 === preg_match('/\pL/u', $this->password)) {
40
            throw new UserSpecificationException('Password must contain at least one letter.');
41
        }
42
    }
43
44
    private function validateNumbers()
45
    {
46
        if (0 === preg_match('/\pN/u', $this->password)) {
47
            throw new UserSpecificationException('Password must contain at least one number.');
48
        }
49
    }
50
51
    private function validateCaseDiff()
52
    {
53
        if (0 === preg_match('/(\p{Ll}+.*\p{Lu})|(\p{Lu}+.*\p{Ll})/u', $this->password)) {
54
            throw new UserSpecificationException('Password must contain at least one uppercase and one lowercase letter.');
55
        }
56
    }
57
58
    private function validateWeakPasswords(): bool
59
    {
60
        $weakList = [
61
            'password',
62
            '12345678',
63
            '123456789',
64
            '1234567890',
65
            'qwertyui',
66
            'baseball',
67
            'football',
68
            'abc12345',
69
            'abcd1234',
70
            'jennifer',
71
            '11111111',
72
            'superman',
73
            'pussycat',
74
        ];
75
76
        if (false === in_array($this->password, $weakList, true)) {
77
            throw new UserSpecificationException('Your password doesn\'t meet our minimum requirements. Please enter a stronger password.');
78
        }
79
    }
80
}
81