-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathIntType.php
More file actions
85 lines (69 loc) · 1.67 KB
/
IntType.php
File metadata and controls
85 lines (69 loc) · 1.67 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
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
<?php
declare(strict_types = 1);
namespace SmartEmailing\Types;
use Nette\Utils\Validators;
use SmartEmailing\Types\Helpers\ExtractableHelpers;
abstract class IntType implements ExtractableTypeInterface
{
final public static function from(
mixed $value
): int {
if (Validators::isNumericInt($value)) {
return (int) $value;
}
if (Validators::isNumeric($value) && \abs((int) $value) === (int) \ceil(\abs((float) $value))) {
return (int) $value;
}
throw InvalidTypeException::typeError('int', $value);
}
final public static function fromOrNull(
mixed $value,
bool $nullIfInvalid = false
): ?int {
if ($value === null) {
return null;
}
try {
return self::from($value);
} catch (InvalidTypeException $e) {
if ($nullIfInvalid) {
return null;
}
throw $e;
}
}
/**
* @param array<mixed>|\ArrayAccess<mixed, mixed> $data
* @throws \SmartEmailing\Types\InvalidTypeException
*/
final public static function extract(
array|\ArrayAccess $data,
string $key
): int {
$value = ExtractableHelpers::extractValue($data, $key);
try {
return self::from($value);
} catch (InvalidTypeException $e) {
throw $e->wrap($key);
}
}
/**
* @param array<mixed>|\ArrayAccess<mixed, mixed> $data
* @throws \SmartEmailing\Types\InvalidTypeException
*/
final public static function extractOrNull(
array|\ArrayAccess $data,
string $key,
bool $nullIfInvalid = false
): ?int {
$value = ExtractableHelpers::extractValueOrNull($data, $key);
if ($value === null) {
return null;
}
try {
return self::fromOrNull($value, $nullIfInvalid);
} catch (InvalidTypeException $exception) {
throw $exception->wrap($key);
}
}
}