Requirements::pattern()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 28
rs 9.6666
cc 3
nc 3
nop 0
1
<?php
2
3
namespace Tleckie\Password;
4
5
use function preg_match;
6
use function sprintf;
7
8
/**
9
 * Class Requirements
10
 *
11
 * @package Tleckie\Password
12
 * @author  Teodoro Leckie Westberg <[email protected]>
13
 */
14
class Requirements implements RequirementsInterface
15
{
16
    /** @var string */
17
    protected const UPPER_REQUIRED = '(?=.*[A-Z])';
18
19
    /** @var string */
20
    protected const LOWER_REQUIRED = '(?=.*[a-z])';
21
22
    /** @var string */
23
    protected const NUMBER_REQUIRED = '(?=.*\d)';
24
25
    /** @var string */
26
    protected const SPECIAL_CHAR_REQUIRED = '(?=.*[_\W])';
27
28
    /** @var int */
29
    protected int $minSize;
30
31
    /** @var bool */
32
    protected bool $sameUpperChar;
33
34
    /** @var bool */
35
    protected bool $sameLowerChar;
36
37
    /** @var bool */
38
    protected bool $sameNumber;
39
40
    /** @var bool */
41
    protected bool $sameSpecialChar;
42
43
    /**
44
     * Requirements constructor.
45
     *
46
     * @param int  $minSize
47
     * @param bool $sameUpperChar
48
     * @param bool $sameNumber
49
     * @param bool $sameSpecialChar
50
     * @param bool $sameLowerChar
51
     */
52
    public function __construct(
53
        int $minSize = 8,
54
        bool $sameUpperChar = true,
55
        bool $sameNumber = true,
56
        bool $sameSpecialChar = true,
57
        bool $sameLowerChar = true
58
    ) {
59
        $this->minSize = $minSize;
60
        $this->sameUpperChar = $sameUpperChar;
61
        $this->sameNumber = $sameNumber;
62
        $this->sameSpecialChar = $sameSpecialChar;
63
        $this->sameLowerChar = $sameLowerChar;
64
    }
65
66
    /**
67
     * @inheritdoc
68
     */
69
    public function isValid(string $password): bool
70
    {
71
        return preg_match(
72
            $this->pattern(),
73
            $password,
74
        );
75
    }
76
77
    /**
78
     * @return string
79
     */
80
    protected function pattern(): string
81
    {
82
        $rules = [
83
            static::UPPER_REQUIRED,
84
            static::NUMBER_REQUIRED,
85
            static::SPECIAL_CHAR_REQUIRED,
86
            static::LOWER_REQUIRED,
87
        ];
88
89
        $requirements = [
90
            $this->sameUpperChar,
91
            $this->sameNumber,
92
            $this->sameSpecialChar,
93
            $this->sameLowerChar
94
        ];
95
96
        $regex = '';
97
98
        foreach ($requirements as $key => $requirement) {
99
            if ($requirement) {
100
                $regex .= $rules[$key];
101
            }
102
        }
103
104
        return sprintf(
105
            '/(%s).{%s,}/',
106
            $regex,
107
            $this->minSize
108
        );
109
    }
110
}
111