-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClampRule.php
More file actions
48 lines (39 loc) · 1.17 KB
/
ClampRule.php
File metadata and controls
48 lines (39 loc) · 1.17 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
<?php
declare(strict_types=1);
namespace KaririCode\Sanitizer\Rule\Numeric;
use KaririCode\Sanitizer\Contract\SanitizationContext;
use KaririCode\Sanitizer\Contract\SanitizationRule;
/**
* Clamps a numeric value to [min, max] bounds.
*
* Parameters: min (int|float), max (int|float).
*
* @author Walmir Silva <walmir.silva@kariricode.org>
*
* @since 3.1.0 ARFA 1.3
*/
final readonly class ClampRule implements SanitizationRule
{
#[\Override]
public function sanitize(mixed $value, SanitizationContext $context): mixed
{
if (! is_numeric($value)) {
return $value;
}
$numeric = \is_int($value) ? $value : (float) $value;
$min = $context->getParameter('min');
$max = $context->getParameter('max');
if (null !== $min && is_numeric($min) && $numeric < $min) {
return \is_int($value) ? (int) $min : (float) $min;
}
if (null !== $max && is_numeric($max) && $numeric > $max) {
return \is_int($value) ? (int) $max : (float) $max;
}
return $value;
}
#[\Override]
public function getName(): string
{
return 'numeric.clamp';
}
}