Min.php
2.65 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
/**
* @license GPL-2.0-or-later
*
* Modified by learndash on 20-September-2023 using Strauss.
* @see https://github.com/BrianHenryIE/strauss
*/
declare(strict_types=1);
namespace StellarWP\Learndash\StellarWP\Validation\Rules;
use Closure;
use StellarWP\Learndash\StellarWP\Validation\Config;
use StellarWP\Learndash\StellarWP\Validation\Contracts\ValidatesOnFrontEnd;
use StellarWP\Learndash\StellarWP\Validation\Contracts\ValidationRule;
use StellarWP\Learndash\StellarWP\Validation\Exceptions\ValidationException;
/**
* @since 1.0.0
*/
class Min implements ValidationRule, ValidatesOnFrontEnd
{
/**
* @var int
*/
private $size;
/**
* @since 1.0.0
*/
public function __construct(int $size)
{
if ($size <= 0) {
Config::throwInvalidArgumentException('Min validation rule requires a non-negative value');
}
$this->size = $size;
}
/**
* @inheritDoc
*
* @since 1.0.0
*/
public static function id(): string
{
return 'min';
}
/**
* @inheritDoc
*
* @since 1.0.0
*/
public static function fromString(string $options = null): ValidationRule
{
if (!is_numeric($options)) {
Config::throwInvalidArgumentException('Min validation rule requires a numeric value');
}
return new self((int)$options);
}
/**
* @inheritDoc
*
* @since 1.0.0
*
* @throws ValidationException
*/
public function __invoke($value, Closure $fail, string $key, array $values)
{
if (is_int($value) || is_float($value)) {
if ($value < $this->size) {
$fail(sprintf(__('%s must be greater than or equal to %d', '%TEXTDOMAIN%'), '{field}', $this->size));
}
} elseif (is_string($value)) {
if (mb_strlen($value) < $this->size) {
$fail(sprintf(__('%s must be more than or equal to %d characters', '%TEXTDOMAIN%'), '{field}', $this->size));
}
} else {
Config::throwValidationException("Field value must be a number or string");
}
}
/**
* @inheritDoc
*
* @since 1.0.0
*/
public function serializeOption(): int
{
return $this->size;
}
/**
* @since 1.0.0
*/
public function getSize(): int
{
return $this->size;
}
/**
* @since 1.0.0
*
* @return void
*/
public function size(int $size)
{
if ($size <= 0) {
Config::throwInvalidArgumentException('Min validation rule requires a non-negative value');
}
$this->size = $size;
}
}