-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractMessage.php
118 lines (94 loc) · 2.74 KB
/
AbstractMessage.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Cqrs;
use ArrayIterator;
use Exception;
use InvalidArgumentException;
use IteratorAggregate;
use JsonSerializable;
use RuntimeException;
use Serializable;
use SonsOfPHP\Contract\Cqrs\MessageInterface;
use Stringable;
use Traversable;
/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
abstract class AbstractMessage implements MessageInterface, JsonSerializable, Serializable, IteratorAggregate
{
private array $payload = [];
/**
* {@inheritdoc}
*/
public function with(string|array $key, mixed $value = null): static
{
if (is_object($value) && !$value instanceof Stringable) {
throw new InvalidArgumentException('$value is invalid');
}
if (is_array($key) && null !== $value) {
throw new InvalidArgumentException('$key is invalid, you cannot pass in $value when $key is an array');
}
if ($value instanceof Stringable) {
$value = (string) $value;
}
if (is_array($key)) {
$that = clone $this;
foreach ($key as $k => $v) {
if (is_object($v) && !$v instanceof Stringable) {
throw new InvalidArgumentException('The array contains invalid values');
}
if ($v instanceof Stringable) {
$v = (string) $v;
}
$that->payload[$k] = $v;
}
return $that;
}
if (array_key_exists($key, $this->payload) && $value === $this->payload[$key]) {
return $this;
}
$that = clone $this;
$that->payload[$key] = $value;
return $that;
}
/**
* {@inheritdoc}
*/
public function get(?string $key = null): mixed
{
if (null === $key) {
return $this->payload;
}
if (!array_key_exists($key, $this->payload)) {
throw new Exception(sprintf('The key "%s" does not exist.', $key));
}
return $this->payload[$key];
}
public function serialize(): ?string
{
if (false === $json = json_encode($this)) {
throw new RuntimeException('Unable to serialize object');
}
return $json;
}
public function unserialize(string $data): void
{
$this->payload = json_decode($data, true);
}
public function __serialize(): array
{
return $this->payload;
}
public function __unserialize(array $data): void
{
$this->payload = $data;
}
public function jsonSerialize(): array
{
return $this->payload;
}
public function getIterator(): Traversable
{
return new ArrayIterator($this->payload);
}
}