1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Antidot\Queue; |
6
|
|
|
|
7
|
|
|
use Assert\Assertion; |
8
|
|
|
use Interop\Queue\Message; |
9
|
|
|
use InvalidArgumentException; |
10
|
|
|
use JsonSerializable; |
11
|
|
|
|
12
|
|
|
class JobPayload implements JsonSerializable |
13
|
|
|
{ |
14
|
|
|
public const INVALID_CONTENT_MESSAGE = 'Invalid message content type "%s" given, it must be array or string type.'; |
15
|
|
|
private string $type; |
16
|
|
|
/** @var string|array */ |
17
|
|
|
private $message; |
18
|
|
|
|
19
|
5 |
|
public static function create(string $messageType, $messageContent): self |
20
|
|
|
{ |
21
|
5 |
|
$self = new self(); |
22
|
5 |
|
$self->type = $messageType; |
23
|
5 |
|
$self->assertValidMessageContent($messageContent); |
24
|
4 |
|
$self->message = $messageContent; |
25
|
|
|
|
26
|
4 |
|
return $self; |
27
|
|
|
} |
28
|
|
|
|
29
|
4 |
|
public static function createFromMessage(Message $message): self |
30
|
|
|
{ |
31
|
4 |
|
$self = new self(); |
32
|
4 |
|
$payload = json_decode($message->getBody(), true, 10, JSON_THROW_ON_ERROR); |
33
|
4 |
|
$self->assertValidMessageData($payload); |
34
|
3 |
|
$self->type = $payload['type']; |
35
|
3 |
|
$self->message = $payload['message']; |
36
|
|
|
|
37
|
3 |
|
return $self; |
38
|
|
|
} |
39
|
|
|
|
40
|
5 |
|
public function type(): string |
41
|
|
|
{ |
42
|
5 |
|
return $this->type; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @return array|string |
47
|
|
|
*/ |
48
|
3 |
|
public function message() |
49
|
|
|
{ |
50
|
3 |
|
return $this->message; |
51
|
|
|
} |
52
|
|
|
|
53
|
5 |
|
private function assertValidMessageContent($messageContent): void |
54
|
|
|
{ |
55
|
5 |
|
if (is_string($messageContent) || is_array($messageContent)) { |
56
|
4 |
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
throw new InvalidArgumentException(sprintf(self::INVALID_CONTENT_MESSAGE, gettype($messageContent))); |
60
|
|
|
} |
61
|
|
|
|
62
|
4 |
|
private function assertValidMessageData($payload): void |
63
|
|
|
{ |
64
|
4 |
|
Assertion::keyExists($payload, 'type', 'The job payload should have the "type" key.'); |
65
|
3 |
|
Assertion::string($payload['type'], 'The job payload kay "type" should have a string value.'); |
66
|
3 |
|
Assertion::keyExists($payload, 'message', 'The job payload should have the "message" key.'); |
67
|
3 |
|
} |
68
|
|
|
|
69
|
2 |
|
public function jsonSerialize(): array |
70
|
|
|
{ |
71
|
|
|
return [ |
72
|
2 |
|
'type' => $this->type, |
73
|
2 |
|
'message' => $this->message, |
74
|
|
|
]; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|