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()); |
|
|
|
|
76
|
|
|
} |
77
|
|
|
} |