|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spatie\Typed; |
|
6
|
|
|
|
|
7
|
|
|
use ArrayAccess; |
|
8
|
|
|
use Spatie\Typed\Excpetions\WrongType; |
|
9
|
|
|
use Spatie\Typed\Excpetions\UninitialisedError; |
|
10
|
|
|
|
|
11
|
|
|
class Struct implements ArrayAccess |
|
12
|
|
|
{ |
|
13
|
|
|
use ValidatesType; |
|
14
|
|
|
|
|
15
|
|
|
/** @var array */ |
|
16
|
|
|
private $types = []; |
|
17
|
|
|
|
|
18
|
|
|
/** @var array */ |
|
19
|
|
|
private $values = []; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(array $types) |
|
22
|
|
|
{ |
|
23
|
|
|
foreach ($types as $field => $type) { |
|
24
|
|
|
if (! $type instanceof Type) { |
|
25
|
|
|
$this->values[$field] = $type; |
|
26
|
|
|
|
|
27
|
|
|
$type = T::infer($type); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
$this->types[$field] = $type; |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function set(array $data): self |
|
35
|
|
|
{ |
|
36
|
|
|
foreach ($this->types as $name => $type) { |
|
37
|
|
|
if (! array_key_exists($name, $data)) { |
|
38
|
|
|
$type = serialize($type); |
|
39
|
|
|
|
|
40
|
|
|
throw WrongType::withMessage("Missing field for this struct: {$name}:{$type}"); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$data[$name] = $this->validateType($type, $data[$name]); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$this->values = $data; |
|
47
|
|
|
|
|
48
|
|
|
return $this; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function offsetGet($offset) |
|
52
|
|
|
{ |
|
53
|
|
|
if (! array_key_exists($offset, $this->values)) { |
|
54
|
|
|
throw UninitialisedError::forField($offset); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $this->values[$offset]; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function offsetSet($offset, $value) |
|
61
|
|
|
{ |
|
62
|
|
|
if ($offset === null) { |
|
63
|
|
|
throw WrongType::withMessage('No field specified'); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$type = $this->types[$offset] ?? null; |
|
67
|
|
|
|
|
68
|
|
|
if (! $type) { |
|
69
|
|
|
throw WrongType::withMessage("No type was configured for this field {$offset}"); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
$this->values[$offset] = $this->validateType($type, $value); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
public function offsetExists($offset) |
|
76
|
|
|
{ |
|
77
|
|
|
return array_key_exists($offset, $this->values); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
public function offsetUnset($offset) |
|
81
|
|
|
{ |
|
82
|
|
|
throw WrongType::withMessage('Struct values cannot be unset'); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
public function toArray(): array |
|
86
|
|
|
{ |
|
87
|
|
|
return $this->values; |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
|
|
public function __get($name) |
|
91
|
|
|
{ |
|
92
|
|
|
return $this[$name]; |
|
93
|
|
|
} |
|
94
|
|
|
|
|
95
|
|
|
public function __set($name, $value) |
|
96
|
|
|
{ |
|
97
|
|
|
$this[$name] = $value; |
|
98
|
|
|
} |
|
99
|
|
|
} |
|
100
|
|
|
|