Completed
Push — master ( 18ed91...48076b )
by Kevin
03:22
created

Payload::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4286
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Zenstruck\Queue;
4
5
use Assert\AssertionFailedException;
6
7
/**
8
 * @author Kevin Bond <[email protected]>
9
 */
10
final class Payload implements \JsonSerializable
11
{
12
    private $serializedEnvelope;
13
    private $metadata;
14
15
    /**
16
     * @param string $json
17
     *
18
     * @return Payload|null
19
     */
20 9
    public static function fromJson($json)
21
    {
22 9
        if (!is_scalar($json)) {
23 2
            return null;
24
        }
25
26 7
        $decodedData = json_decode($json, true);
27
28 7
        if (JSON_ERROR_NONE !== json_last_error()) {
29 2
            return null;
30
        }
31
32 6
        if (!is_array($decodedData)) {
33 1
            return null;
34
        }
35
36 5
        return self::fromArray($decodedData);
37
    }
38
39
    /**
40
     * @param array $array
41
     *
42
     * @return Payload|null
43
     */
44 7
    public static function fromArray(array $array)
45
    {
46 7
        if (!isset($array['serialized_envelope']) || !isset($array['metadata'])) {
47 1
            return null;
48
        }
49
50
        try {
51 6
            \Assert\that($array['serialized_envelope'])->string();
52 5
            \Assert\that($array['metadata'])->string();
53 6
        } catch (AssertionFailedException $e) {
54 2
            return null;
55
        }
56
57 4
        return new self($array['serialized_envelope'], $array['metadata']);
58
    }
59
60
    /**
61
     * @param string $serializedEnvelope
62
     * @param string $metadata
63
     */
64 22
    public function __construct($serializedEnvelope, $metadata)
65
    {
66 22
        $this->serializedEnvelope = $serializedEnvelope;
67 22
        $this->metadata = $metadata;
68 22
    }
69
70
    /**
71
     * @return string
72
     */
73 10
    public function serializedEnvelope()
74
    {
75 10
        return $this->serializedEnvelope;
76
    }
77
78
    /**
79
     * @return string
80
     */
81 6
    public function metadata()
82
    {
83 6
        return $this->metadata;
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 4
    public function jsonSerialize()
90
    {
91
        return [
92 4
            'serialized_envelope' => $this->serializedEnvelope,
93 4
            'metadata' => $this->metadata,
94 4
        ];
95
    }
96
}
97