This repository was archived by the owner on Apr 26, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIsNumeric.php
More file actions
51 lines (42 loc) · 1.53 KB
/
Copy pathIsNumeric.php
File metadata and controls
51 lines (42 loc) · 1.53 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
<?php
declare(strict_types=1);
namespace Hsnfirdaus\ClassValidator\Attribute;
use Attribute;
use Hsnfirdaus\ClassValidator\Error\PropertyError;
use ReflectionProperty;
use function is_numeric;
use function strlen;
/**
* Validate the value is numeric using php `is_numeric` function
*/
#[Attribute(Attribute::TARGET_PROPERTY)]
class IsNumeric implements ValidationAttribute
{
/**
* @param int|null $length Fixed length
* @param int|null $minLength Minimum number length
* @param int|null $maxLength Maximum number length
*/
public function __construct(
private int|null $length = null,
private int|null $minLength = null,
private int|null $maxLength = null,
) {
}
public function validateProperty(ReflectionProperty $property, object $object): void
{
$value = $property->getValue($object);
if (! is_numeric($value)) {
throw new PropertyError($property, 'NUMERIC_INVALID');
}
if (isset($this->length) && strlen((string) $value) !== $this->length) {
throw new PropertyError($property, 'NUMERIC_INVALID_LENGTH', $this->length);
}
if (isset($this->minLength) && strlen((string) $value) < $this->minLength) {
throw new PropertyError($property, 'NUMERIC_INVALID_MIN_LENGTH', $this->minLength);
}
if (isset($this->maxLength) && strlen((string) $value) > $this->maxLength) {
throw new PropertyError($property, 'NUMERIC_INVALID_MAX_LENGTH', $this->maxLength);
}
}
}