NameValidator   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A validate() 0 17 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
15
use Phypes\Error\TypeError;
16
use Phypes\Error\TypeErrorCode;
17
use Phypes\Result\Failure;
18
use Phypes\Result\Result;
19
use Phypes\Result\Success;
20
use Phypes\Rule\Aggregate\ForAll;
21
use Phypes\Rule\CharType\Alpha;
22
use Phypes\Rule\String\MaximumLength;
23
use Phypes\Rule\String\MinimumLength;
24
25
class NameValidator implements Validator
26
{
27
    /**
28
     * @var int $minLength
29
     */
30
    private $minLength;
31
    /**
32
     * @var int $maxLength
33
     */
34
    private $maxLength;
35
    /**
36
     * @var array $allowedChars
37
     */
38
    private $allowedChars = [];
39
40
    /**
41
     * NameValidator constructor.
42
     * Supply parameters depending on domain specific name requirements
43
     * @param int $minLength
44
     * @param int $maxLength
45
     * @param array $allowedChars
46
     */
47
    public function __construct(int $minLength = 1, int $maxLength = 255, $allowedChars = ["\'", "-", ".", " "])
48
    {
49
        $this->minLength = $minLength;
50
        $this->maxLength = $maxLength;
51
        $this->allowedChars = $allowedChars;
52
    }
53
54
    /**
55
     * @param $name
56
     * @return Result
57
     * @throws \Phypes\Exception\InvalidRule
58
     */
59
    public function validate($name): Result
60
    {
61
        $rule = new ForAll(
62
            new MinimumLength($this->minLength),
63
            new MaximumLength($this->maxLength),
64
            new Alpha($this->allowedChars)
65
        );
66
67
        $result = $rule->validate($name);
68
69
        if ($result->isValid())
70
            return new Success();
71
        /**
72
         * @var Failure $result
73
         */
74
        return new Failure(new TypeError(TypeErrorCode::NAME_INVALID, 'Invalid name format'),
75
            $result->getErrors());
0 ignored issues
show
Bug introduced by
$result->getErrors() of type array<integer,Phypes\Error\Error> is incompatible with the type Phypes\Error\Error expected by parameter $errors of Phypes\Result\Failure::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

75
            /** @scrutinizer ignore-type */ $result->getErrors());
Loading history...
76
    }
77
}