PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.16.8.1
GiveWP – Donation Plugin and Fundraising Platform v4.16.8.1
4.16.9 4.16.8.1 4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 2.30.0 All 255 releases
give / src / DonationForms / Rules / Size.php

Size.php in GiveWP – Donation Plugin and Fundraising Platform 4.16.8.1, at src/DonationForms/Rules/Size.php

119 lines 2.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Give\DonationForms\Rules;
3
4
5 use Closure;
6 use Give\Vendors\StellarWP\Validation\Config;
7 use Give\Vendors\StellarWP\Validation\Contracts\ValidatesOnFrontEnd;
8 use Give\Vendors\StellarWP\Validation\Contracts\ValidationRule;
9
10 use function is_numeric;
11
12 class Size implements ValidationRule, ValidatesOnFrontEnd
13 {
14 /**
15 * @var numeric
16 */
17 protected $size;
18
19 /**
20 * @inheritDoc
21 */
22 public static function id(): string
23 {
24 return 'size';
25 }
26
27 /**
28 * @since 3.0.0
29 */
30 public function __construct($size)
31 {
32 if ($size <= 0) {
33 Config::throwInvalidArgumentException('Size validation rule requires a non-negative value');
34 }
35
36 $this->size = $this->sanitize($size);
37 }
38
39 public function sanitize($value)
40 {
41 if (is_numeric($value)) {
42 if (strpos($value, '.') !== false) {
43 return (float)$value;
44 }
45
46 return (int)$value;
47 }
48
49 return $value;
50 }
51
52 /**
53 * @since 3.0.0
54 */
55 public static function fromString(string $options = null): ValidationRule
56 {
57 if (!is_numeric($options)) {
58 Config::throwInvalidArgumentException('Size validation rule requires a numeric value');
59 }
60
61 return new self($options);
62 }
63
64 /**
65 * @since 3.0.0
66 */
67 public function __invoke($value, Closure $fail, string $key, array $values)
68 {
69 $value = $this->sanitize($value);
70
71 if (is_numeric($value)) {
72 if ($value !== $this->getSize()) {
73 $fail(sprintf(__('%s must be exactly %s', 'give'), '{field}', $this->getSize()));
74 }
75 } elseif (is_string($value)) {
76 if (mb_strlen($value) !== $this->getSize()) {
77 $fail(sprintf(__('%s must be exactly %d characters', 'give'), '{field}', $this->getSize()));
78 }
79 } else {
80 Config::throwValidationException("Field value must be a number or string");
81 }
82 }
83
84 /**
85 * @since 3.0.0
86 *
87 * @return numeric
88 */
89 public function serializeOption()
90 {
91 return $this->size;
92 }
93
94 /**
95 * @since 3.0.0
96 *
97 * @return numeric
98 */
99 public function getSize()
100 {
101 return $this->size;
102 }
103
104 /**
105 * @since 3.0.0
106 *
107 * @param numeric $size
108 *
109 * @return void
110 */
111 public function size($size)
112 {
113 if ($size <= 0) {
114 Config::throwInvalidArgumentException('Size validation rule requires a non-negative value');
115 }
116
117 $this->size = $size;
118 }
119 }