1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BenTools\MercurePHP\Model; |
4
|
|
|
|
5
|
|
|
final class Message implements \JsonSerializable |
6
|
|
|
{ |
7
|
|
|
private string $id; |
8
|
|
|
private ?string $data; |
9
|
|
|
private bool $private; |
10
|
|
|
private ?string $event; |
11
|
|
|
private ?int $retry; |
12
|
|
|
|
13
|
|
|
public function __construct( |
14
|
|
|
string $id, |
15
|
|
|
string $data = null, |
16
|
|
|
bool $private = false, |
17
|
|
|
?string $event = null, |
18
|
|
|
?int $retry = null |
19
|
|
|
) { |
20
|
|
|
$this->id = $id; |
21
|
|
|
$this->data = $data; |
22
|
|
|
$this->private = $private; |
23
|
|
|
$this->event = $event; |
24
|
|
|
$this->retry = $retry; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function getId(): string |
28
|
|
|
{ |
29
|
|
|
return $this->id; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function getData(): ?string |
33
|
|
|
{ |
34
|
|
|
return $this->data; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function isPrivate(): bool |
38
|
|
|
{ |
39
|
|
|
return $this->private; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function __toString(): string |
43
|
|
|
{ |
44
|
|
|
$output = 'id:' . $this->id . \PHP_EOL; |
45
|
|
|
|
46
|
|
|
if (null !== $this->event) { |
47
|
|
|
$output .= 'event:' . $this->event . \PHP_EOL; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (null !== $this->retry) { |
51
|
|
|
$output .= 'retry:' . $this->retry . \PHP_EOL; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if (null !== $this->data) { |
55
|
|
|
// If $data contains line breaks, we have to serialize it in a different way |
56
|
|
|
if (false !== \strpos($this->data, \PHP_EOL)) { |
57
|
|
|
$lines = \explode(\PHP_EOL, $this->data); |
58
|
|
|
foreach ($lines as $line) { |
59
|
|
|
$output .= 'data:' . $line . \PHP_EOL; |
60
|
|
|
} |
61
|
|
|
} else { |
62
|
|
|
$output .= 'data:' . $this->data . \PHP_EOL; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $output . \PHP_EOL; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function jsonSerialize(): array |
70
|
|
|
{ |
71
|
|
|
return \array_filter( |
72
|
|
|
[ |
73
|
|
|
'id' => $this->id, |
74
|
|
|
'data' => $this->data, |
75
|
|
|
'private' => $this->private, |
76
|
|
|
'event' => $this->event, |
77
|
|
|
'retry' => $this->retry, |
78
|
|
|
], |
79
|
|
|
fn ($value) => null !== $value |
80
|
|
|
); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public static function fromArray(array $event): self |
84
|
|
|
{ |
85
|
|
|
return new self( |
86
|
|
|
$event['id'], |
87
|
|
|
$event['data'] ?? null, |
88
|
|
|
$event['private'] ?? false, |
89
|
|
|
$event['type'] ?? null, |
90
|
|
|
$event['retry'] ?? null, |
91
|
|
|
); |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|