Completed
Push — master ( 257530...5ee91e )
by Camilo
01:42
created

DatedPayload::getPayload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1
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