-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringRule.php
More file actions
96 lines (79 loc) · 2.31 KB
/
StringRule.php
File metadata and controls
96 lines (79 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
namespace Elie\Validator\Rule;
/**
* This class verifies that a value is a valid string.
*/
class StringRule extends AbstractRule
{
/**#@+
* Specific message error code
*/
public const INVALID_STRING = 'invalidString';
public const INVALID_STRING_LENGTH = 'invalidStringLength';
/**#@-*/
/**#@+
* Specific options for StringRule
*/
public const TRIM = 'trim';
public const MIN = 'min';
public const MAX = 'max';
/**#@-*/
/**
* Minimum string length.
*/
protected int $min = 0;
/**
* Maximum string length.
*/
protected ?int $max = null;
/**
* Params could have the following structure:
* <code>
* [
* 'required' => {bool:optional:false by default},
* 'trim' => {bool:optional:true by default},
* 'messages' => {array:optional:key/value message patterns},
* 'min' => {int:optional:0 by default},
* 'max' => {int:optional:value length by default}
* ]
* </code>
*/
public function __construct(int|string $key, mixed $value, array $params = [])
{
parent::__construct($key, $value, $params);
if (isset($params[$this::MIN])) {
$this->min = (int)$params[$this::MIN];
}
if (isset($params[$this::MAX])) {
$this->max = (int)$params[$this::MAX];
}
$this->messages += [
$this::INVALID_STRING => '%key% does not have a string value: %value%',
$this::INVALID_STRING_LENGTH => '%key%: The length of %value% is not between %min% and %max%',
];
}
public function validate(): int
{
$run = parent::validate();
if ($run !== $this::CHECK) {
return $run;
}
if (!is_string($this->value)) {
return $this->setAndReturnError($this::INVALID_STRING);
}
return $this->checkMinMax();
}
protected function checkMinMax(): int
{
$len = strlen($this->value);
$maxOrLen = $this->max ?: $len;
if ($len < $this->min || $len > $maxOrLen) {
return $this->setAndReturnError($this::INVALID_STRING_LENGTH, [
'%min%' => $this->min,
'%max%' => $this->max,
]);
}
return $this::VALID;
}
}