generated from inherelab/php-pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLenValidator.php
113 lines (99 loc) · 2.38 KB
/
LenValidator.php
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php declare(strict_types=1);
/**
* This file is part of toolkit/pflag.
*
* @link https://github.com/php-toolkit
* @author https://github.com/inhere
* @license MIT
*/
namespace Toolkit\PFlag\Validator;
use Toolkit\PFlag\Exception\FlagException;
use function count;
use function is_array;
use function is_string;
use function sprintf;
use function strlen;
use function trim;
/**
* class LenValidator
*/
class LenValidator extends AbstractValidator
{
/**
* @var int|null
*/
protected ?int $min;
/**
* @var int|null
*/
protected ?int $max;
/**
* @param int|null $min
* @param int|null $max
*
* @return static
*/
public static function new(?int $min = null, ?int $max = null): self
{
return new static($min, $max);
}
/**
* Class constructor.
*
* @param int|null $min
* @param int|null $max
*/
public function __construct(?int $min = null, ?int $max = null)
{
$this->min = $min;
$this->max = $max;
}
/**
* @param mixed $value
* @param string $name
*
* @return bool
*/
public function checkInput(mixed $value, string $name): bool
{
if (is_string($value)) {
$len = strlen(trim($value));
} elseif (is_array($value)) {
$len = count($value);
} else {
return false;
}
// if ($this->min !== null && $this->max !== null) {
// return sprintf('Len: %d - %d', $this->min, $this->max);
// }
//
// if ($this->min !== null) {
// return sprintf('Len: >= %d', $this->min);
// }
//
// if ($this->max !== null) {
// return sprintf('Len: <= %d', $this->max);
// }
// if (empty($value)) {
// throw new FlagException("flag '$name' value cannot be empty");
// }
return true;
}
/**
* @return string
*/
public function __toString(): string
{
if ($this->min !== null && $this->max !== null) {
return sprintf('Len: %d - %d', $this->min, $this->max);
}
if ($this->min !== null) {
return sprintf('Len: >= %d', $this->min);
}
if ($this->max !== null) {
return sprintf('Len: <= %d', $this->max);
}
// not limit
return '';
}
}