forked from phillies2k/ratchet-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Payload.php
137 lines (121 loc) · 2.6 KB
/
Payload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
/**
* This file is part of the RatchetBundle project.
*
* (c) 2013 Philipp Boes <mostgreedy@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace P2\Bundle\RatchetBundle\WebSocket;
/**
* Class Payload
* @package P2\Bundle\RatchetBundle\WebSocket
*/
class Payload
{
/**
* @var string
*/
protected $event;
/**
* @var array
*/
protected $data;
/**
* Validates the given json data format. Returns true when the given json format is valid, false otherwise.
*
* @param array $json
*
* @return boolean
*/
public static function isValid(array $json)
{
if (!isset($json['event'])) {
return false;
}
if (!isset($json['data'])) {
return false;
}
return true;
}
/**
* Decodes the given string input and returns an array of data for this payload.
* Throws InvalidArgumentException on decoding errors.
*
* @param string $msg
*
* @return array
* @throws \InvalidArgumentException
*/
public static function decode($msg)
{
try {
$data = json_decode($msg, true);
return $data;
} catch (\Exception $e) {
throw new \InvalidArgumentException('Invalid json format');
}
}
/**
* @return string
*/
public function encode()
{
return json_encode(
array(
'event' => $this->getEvent(),
'data' => $this->getData()
)
);
}
/**
* @param string $json
*
* @return Payload
*/
public static function createFromJson($json)
{
return static::createFromArray(static::decode($json));
}
/**
* @param array $data
*
* @return Payload
*/
public static function createFromArray($data)
{
if (!is_array($data)) {
return null;
}
if (static::isValid($data)) {
return new static($data['event'], $data['data']);
}
return null;
}
/**
* @param string $event
* @param mixed $data
*/
public function __construct($event, $data)
{
$this->event = $event;
$this->data = $data;
}
/**
* Returns the data for this payload.
*
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* @return string
*/
public function getEvent()
{
return $this->event;
}
}