Passed
Push — master ( ae9f09...aff02c )
by Dedipyaman
01:51
created

PasswordValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
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\InvalidRuleOption
43
     * @throws \Phypes\Exception\InvalidAggregateRule
44
     */
45
    public function validate($password): Result
46
    {
47
        $atleast = new ForAtLeast($this->minCharStrength,
48
            new ContainsPattern(ContainsPattern::UPPERCASE),
49
            new ContainsPattern(ContainsPattern::LOWERCASE),
50
            new ContainsPattern(ContainsPattern::SPECIAL_CHARS),
51
            new ContainsPattern(ContainsPattern::NUMBER)
52
        );
53
54
        $rule = new ForAll(
55
            $atleast,
56
            new MinimumLength($this->minLength));
57
58
        $result = $rule->validate($password);
59
60
        if ($result->isValid())
61
            return new Success();
62
        /**
63
         * @var Failure $result
64
         */
65
        return new Failure(new TypeError(TypeErrorCode::PASSWORD_INVALID, 'Invalid password'),
66
            ...$result->getErrors());
67
    }
68
}