UsernameValidator   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 16
c 3
b 0
f 0
dl 0
loc 42
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A validate() 0 15 2
1
<?php
2
/*
3
 * This file is part of Phypes <https://github.com/2DSharp/Phypes>.
4
 *
5
 * (c) Dedipyaman Das <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
12
namespace Phypes\Validator;
13
14
use Phypes\Error\TypeError;
15
use Phypes\Error\TypeErrorCode;
16
use Phypes\Result\Failure;
17
use Phypes\Result\Result;
18
use Phypes\Result\Success;
19
use Phypes\Rule\Aggregate\ForAll;
20
use Phypes\Rule\CharType\AlphaNumeric;
21
use Phypes\Rule\String\MaximumLength;
22
use Phypes\Rule\String\MinimumLength;
23
24
class UsernameValidator implements Validator
25
{
26
    /**
27
     * @var integer $minLength
28
     */
29
    private $minLength;
30
    /**
31
     * @var integer $maxLength
32
     */
33
    private $maxLength;
34
    /**
35
     * @var array $allowedChars
36
     */
37
    private $allowedSpecialChars = [];
38
39
    public function __construct(int $minLength = 4, int $maxLength = 12, $allowedSpecialChars = [])
40
    {
41
        $this->minLength = $minLength;
42
        $this->maxLength = $maxLength;
43
        $this->allowedSpecialChars = $allowedSpecialChars;
44
    }
45
46
    /**
47
     * @param $username
48
     * @return Result
49
     * @throws \Phypes\Exception\InvalidRule
50
     */
51
    public function validate($username): Result
52
    {
53
        $rule = new ForAll(
54
            new AlphaNumeric($this->allowedSpecialChars),
55
            new MinimumLength($this->minLength),
56
            new MaximumLength($this->maxLength));
57
58
        $result = $rule->validate($username);
59
        if ($result->isValid())
60
            return new Success();
61
        /**
62
         * @var Failure $result
63
         */
64
        return new Failure(new TypeError(TypeErrorCode::USERNAME_INVALID, 'Invalid Username format'),
65
            ...$result->getErrors());
66
67
68
    }
69
}