-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathNumber.php
79 lines (59 loc) · 1.68 KB
/
Number.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
<?php
declare(strict_types=1);
namespace Palmtree\Form\Constraint;
class Number extends AbstractConstraint implements ConstraintInterface
{
final public const ERROR_NOT_NUMERIC = 1;
final public const ERROR_TOO_SMALL = 2;
final public const ERROR_TOO_LARGE = 4;
private ?int $errorCode = null;
private ?int $min = null;
private ?int $max = null;
public function validate(mixed $input): bool
{
if (!is_numeric($input)) {
$this->errorCode = self::ERROR_NOT_NUMERIC;
return false;
}
if ($this->min !== null && $input < $this->min) {
$this->errorCode = self::ERROR_TOO_SMALL;
return false;
}
if ($this->max !== null && $input > $this->max) {
$this->errorCode = self::ERROR_TOO_LARGE;
return false;
}
return true;
}
public function getMin(): ?int
{
return $this->min;
}
public function setMin(?int $min): self
{
$this->min = $min;
return $this;
}
public function getMax(): ?int
{
return $this->max;
}
public function setMax(?int $max): self
{
$this->max = $max;
return $this;
}
public function getErrorCode(): ?int
{
return $this->errorCode;
}
public function getErrorMessage(): string
{
$errorMessage = match ($this->errorCode) {
self::ERROR_TOO_SMALL => "This value must be greater than or equal to $this->min",
self::ERROR_TOO_LARGE => "This value must be less than $this->max",
default => 'This value must be a number',
};
return $errorMessage;
}
}