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
|
|
|
use Phypes\Rule\String\TextCase; |
15
|
|
|
|
16
|
|
|
class PasswordValidator implements Validator |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Validate the password based on different imposing conditions |
20
|
|
|
* Implement your own password validator if you want a more custom set of rules |
21
|
|
|
* This set of rules should work for a lot of general use cases |
22
|
|
|
* @param $password |
23
|
|
|
* @return Result |
24
|
|
|
* @throws \Phypes\Exception\InvalidRuleOption |
25
|
|
|
* @throws \Phypes\Exception\InvalidAggregateRule |
26
|
|
|
*/ |
27
|
|
|
public function validate($password): Result |
28
|
|
|
{ |
29
|
|
|
$atleast = new ForAtLeast(2, |
30
|
|
|
new ContainsPattern(ContainsPattern::UPPERCASE), |
31
|
|
|
new ContainsPattern(ContainsPattern::LOWERCASE), |
32
|
|
|
new ContainsPattern(ContainsPattern::SPECIAL_CHARS), |
33
|
|
|
new ContainsPattern(ContainsPattern::NUMBER) |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
$rule = new ForAll( |
37
|
|
|
$atleast, |
38
|
|
|
new MinimumLength(8)); |
39
|
|
|
|
40
|
|
|
$result = $rule->validate($password); |
41
|
|
|
|
42
|
|
|
if ($result->isValid()) |
43
|
|
|
return new Success(); |
44
|
|
|
/** |
45
|
|
|
* @var Failure $result |
46
|
|
|
*/ |
47
|
|
|
return new Failure(new TypeError(TypeErrorCode::PASSWORD_INVALID, 'Invalid password'), |
48
|
|
|
...$result->getErrors()); |
49
|
|
|
} |
50
|
|
|
} |