|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace unreal4u\MQTT\Application; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Log\LoggerInterface; |
|
8
|
|
|
use unreal4u\MQTT\DummyLogger; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* This is an example of a payload class that performs some processing on the data |
|
12
|
|
|
* |
|
13
|
|
|
* This particular case will prepend a datetime to the message itself. It will json_encode() it into the payload and |
|
14
|
|
|
* when retrieving it will set the public property $originalPublishDateTime. |
|
15
|
|
|
*/ |
|
16
|
|
|
final class DatedPayload implements PayloadInterface |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* The actual payload contents |
|
20
|
|
|
* @var string |
|
21
|
|
|
*/ |
|
22
|
|
|
private $payload = ''; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var \DateTimeImmutable |
|
26
|
|
|
*/ |
|
27
|
|
|
public $originalPublishDateTime; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @var LoggerInterface |
|
31
|
|
|
*/ |
|
32
|
|
|
private $logger; |
|
33
|
|
|
|
|
34
|
5 |
|
public function __construct(string $messageContents = null, LoggerInterface $logger = null) |
|
35
|
|
|
{ |
|
36
|
|
|
// Set the logger before setting the payload so that we already have it in the object |
|
37
|
5 |
|
if ($logger === null) { |
|
38
|
5 |
|
$logger = new DummyLogger(); |
|
39
|
|
|
} |
|
40
|
5 |
|
$this->logger = $logger; |
|
41
|
|
|
|
|
42
|
5 |
|
if ($messageContents !== null) { |
|
43
|
2 |
|
$this->setPayload($messageContents); |
|
44
|
|
|
} |
|
45
|
5 |
|
} |
|
46
|
|
|
|
|
47
|
3 |
|
public function setPayload(string $contents): PayloadInterface |
|
48
|
|
|
{ |
|
49
|
3 |
|
$this->payload = $contents; |
|
50
|
3 |
|
$this->originalPublishDateTime = new \DateTimeImmutable('now'); |
|
51
|
3 |
|
return $this; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
3 |
|
public function getPayload(): string |
|
55
|
|
|
{ |
|
56
|
3 |
|
return $this->payload; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
1 |
|
public function processIncomingPayload(string $contents): PayloadInterface |
|
60
|
|
|
{ |
|
61
|
1 |
|
$this->logger->debug('Processing incoming payload'); |
|
62
|
1 |
|
$decodedData = json_decode($contents, true); |
|
63
|
1 |
|
$this->originalPublishDateTime = new \DateTimeImmutable($decodedData['publishDateTime']); |
|
64
|
1 |
|
$this->payload = $decodedData['payload']; |
|
65
|
1 |
|
return $this; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
1 |
|
public function getProcessedPayload(): string |
|
69
|
|
|
{ |
|
70
|
1 |
|
return json_encode(['publishDateTime' => date('r'), 'payload' => $this->payload]); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|