1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Phypes\Validator; |
4
|
|
|
|
5
|
|
|
use Phypes\Error\TypeError; |
6
|
|
|
use Phypes\Error\TypeErrorCode; |
7
|
|
|
use Phypes\Result\Failure; |
8
|
|
|
use Phypes\Result\Result; |
9
|
|
|
use Phypes\Result\Success; |
10
|
|
|
use Phypes\Rule\Aggregate\ForAll; |
11
|
|
|
use Phypes\Rule\Aggregate\ForAtLeast; |
12
|
|
|
use Phypes\Rule\Pattern\ContainsPattern; |
13
|
|
|
use Phypes\Rule\String\MinimumLength; |
14
|
|
|
|
15
|
|
|
class PasswordValidator implements Validator |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var int $minLength |
19
|
|
|
*/ |
20
|
|
|
private $minLength; |
21
|
|
|
/** |
22
|
|
|
* @var int $minCharStrength |
23
|
|
|
*/ |
24
|
|
|
private $minCharStrength; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* PasswordValidator constructor. |
28
|
|
|
* @param int $minLength |
29
|
|
|
* @param int $minCharStrength Minimum variety in characters |
30
|
|
|
*/ |
31
|
|
|
public function __construct(int $minLength = 8, int $minCharStrength = 2) |
32
|
|
|
{ |
33
|
|
|
$this->minLength = $minLength; |
34
|
|
|
$this->minCharStrength = $minCharStrength; |
35
|
|
|
} |
36
|
|
|
/** |
37
|
|
|
* Validate the password based on different imposing conditions |
38
|
|
|
* Implement your own password validator if you want a more custom set of rules |
39
|
|
|
* This set of rules should work for a lot of general use cases |
40
|
|
|
* @param $password |
41
|
|
|
* @return Result |
42
|
|
|
* @throws \Phypes\Exception\InvalidRule |
43
|
|
|
*/ |
44
|
|
|
public function validate($password): Result |
45
|
|
|
{ |
46
|
|
|
$atleast = new ForAtLeast($this->minCharStrength, |
47
|
|
|
new ContainsPattern(ContainsPattern::UPPERCASE), |
48
|
|
|
new ContainsPattern(ContainsPattern::LOWERCASE), |
49
|
|
|
new ContainsPattern(ContainsPattern::SPECIAL_CHARS), |
50
|
|
|
new ContainsPattern(ContainsPattern::NUMBER) |
51
|
|
|
); |
52
|
|
|
|
53
|
|
|
$rule = new ForAll( |
54
|
|
|
$atleast, |
55
|
|
|
new MinimumLength($this->minLength)); |
56
|
|
|
|
57
|
|
|
$result = $rule->validate($password); |
58
|
|
|
|
59
|
|
|
if ($result->isValid()) |
60
|
|
|
return new Success(); |
61
|
|
|
/** |
62
|
|
|
* @var Failure $result |
63
|
|
|
*/ |
64
|
|
|
return new Failure(new TypeError(TypeErrorCode::PASSWORD_INVALID, 'Invalid password'), |
65
|
|
|
...$result->getErrors()); |
66
|
|
|
} |
67
|
|
|
} |