-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
StrictTypeArray.php
95 lines (68 loc) · 1.9 KB
/
StrictTypeArray.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php declare(strict_types=1);
namespace h4kuna\DataType\Collection;
use h4kuna\DataType\Basic\Bools;
use h4kuna\DataType\Basic\Floats;
use h4kuna\DataType\Basic\Integer;
use h4kuna\DataType\Basic\Strings;
use h4kuna\DataType\Exceptions\InvalidTypeException;
final class StrictTypeArray
{
/**
* @param array<string, mixed> $data
*/
public function __construct(private /* readonly */ array $data)
{
}
public function stringNull(string $name): ?string
{
return isset($this->data[$name]) ? Strings::from($this->data[$name]) : null;
}
public function string(string $name): string
{
array_key_exists($name, $this->data) || throw InvalidTypeException::invalidString($name);
return Strings::from($this->data[$name]);
}
public function float(string $name): float
{
array_key_exists($name, $this->data) || throw InvalidTypeException::invalidFloat($name);
return Floats::from($this->data[$name]);
}
public function floatNull(string $name): ?float
{
return isset($this->data[$name]) ? Floats::from($this->data[$name]) : null;
}
public function int(string $name): int
{
array_key_exists($name, $this->data) || throw InvalidTypeException::invalidInt($name);
return Integer::from($this->data[$name]);
}
public function intNull(string $name): ?int
{
return isset($this->data[$name]) ? Integer::from($this->data[$name]) : null;
}
public function bool(string|float|int $name): bool
{
if (isset($this->data[$name]) === false) {
return false;
}
return Bools::from($this->data[$name]);
}
/**
* @return array<string>|null
*/
public function arrayNull(string $name): ?array
{
return isset($this->data[$name]) ? $this->array($name) : null;
}
/**
* @return array<string>
*/
public function array(string $name): array
{
$value = $this->data[$name] ?? null;
if (is_array($value) === false) {
throw InvalidTypeException::invalidArray($name);
}
return $value;
}
}