Completed
Pull Request — master (#3)
by Kevin
03:40
created

Payload::fromJson()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 6.7441

Importance

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