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
|
<?php
declare(strict_types=1);
namespace StellarWP\Validation\Rules;
use Closure; use StellarWP\Validation\Config; use StellarWP\Validation\Contracts\ValidatesOnFrontEnd; use StellarWP\Validation\Contracts\ValidationRule; use StellarWP\Validation\Exceptions\ValidationException;
/** * @since 1.0.0 */ class Max implements ValidationRule, ValidatesOnFrontEnd { /** * @var int */ private $size;
/** * @since 1.0.0 */ public function __construct(int $size) { if ($size <= 0) { Config::throwInvalidArgumentException('Max validation rule requires a non-negative value'); }
$this->size = $size; }
/** * @inheritDoc * * @since 1.0.0 */ public static function id(): string { return 'max'; }
/** * @inheritDoc * * @since 1.0.0 */ public static function fromString(string $options = null): ValidationRule { if (!is_numeric($options)) { Config::throwInvalidArgumentException('Max 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 less than or equal to %d', '%TEXTDOMAIN%'), '{field}', $this->size)); } } elseif (is_string($value)) { if (mb_strlen($value) > $this->size) { $fail(sprintf(__('%s must be less 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('Max validation rule requires a non-negative value'); }
$this->size = $size; } }
|