1
|
|
|
<?php |
2
|
|
|
namespace Hyphper\Frame; |
3
|
|
|
|
4
|
|
|
use Hyphper\Frame\Exception\InvalidFrameException; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* The PING frame is a mechanism for measuring a minimal round-trip time from |
8
|
|
|
* the sender, as well as determining whether an idle connection is still |
9
|
|
|
* functional. PING frames can be sent from any endpoint. |
10
|
|
|
* |
11
|
|
|
* @package Hyphper\Frame |
12
|
|
|
*/ |
13
|
|
|
class PingFrame extends \Hyphper\Frame |
14
|
|
|
{ |
15
|
|
|
protected $defined_flags = [Flag::ACK]; |
16
|
|
|
protected $type = 0x06; |
17
|
|
|
protected $stream_association = self::NO_STREAM; |
18
|
|
|
protected $opaque_data; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* PingFrame constructor. |
22
|
|
|
* |
23
|
|
|
* @param array $options |
24
|
|
|
*/ |
25
|
7 |
|
public function __construct(array $options = []) |
26
|
|
|
{ |
27
|
7 |
|
parent::__construct($options); |
28
|
|
|
|
29
|
6 |
|
$this->opaque_data = $options['opaque_data'] ?? ''; |
30
|
6 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @return string |
34
|
|
|
* @throws InvalidFrameException |
35
|
|
|
*/ |
36
|
2 |
|
public function serializeBody(): string |
37
|
|
|
{ |
38
|
2 |
|
if (strlen($this->opaque_data) > 8) { |
39
|
1 |
|
throw new InvalidFrameException( |
40
|
1 |
|
sprintf('PING frame may not have more than 8 bytes of data, got %d', strlen($this->opaque_data)) |
41
|
|
|
); |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
$data = $this->opaque_data; |
45
|
1 |
|
$data = str_pad($data, 8, "\x00", STR_PAD_RIGHT); |
46
|
|
|
|
47
|
1 |
|
return $data; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Given the body of a frame, parses it into frame data. This populates |
52
|
|
|
* the non-header parts of the frame: that is, it does not populate the |
53
|
|
|
* stream ID or flags. |
54
|
|
|
* |
55
|
|
|
* |
56
|
|
|
* @param string $data |
57
|
|
|
* |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
3 |
|
public function parseBody(string $data) |
61
|
|
|
{ |
62
|
3 |
|
if (strlen($data) != 8) { |
63
|
2 |
|
throw new InvalidFrameException( |
64
|
2 |
|
sprintf('PING frame must have 8 byte length, got %d', strlen($data)) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
$this->opaque_data = $data; |
69
|
1 |
|
$this->body_len = strlen($data); |
70
|
1 |
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
1 |
|
public function getOpaqueData(): string |
76
|
|
|
{ |
77
|
1 |
|
return $this->opaque_data; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @param string $opaque_data |
82
|
|
|
* @return $this |
83
|
|
|
*/ |
84
|
2 |
|
public function setOpaqueData(string $opaque_data) |
85
|
|
|
{ |
86
|
2 |
|
$this->opaque_data = $opaque_data; |
87
|
2 |
|
return $this; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|